TweetXer

Delete all your Tweets for free.

目前为 2024-11-22 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name TweetXer
  3. // @namespace https://github.com/lucahammer/tweetXer/
  4. // @version 0.7.4
  5. // @description Delete all your Tweets for free.
  6. // @author Luca,dbort,pReya,Micolithe,STrRedWolf
  7. // @license NoHarm-draft
  8. // @match https://x.com/*
  9. // @match https://mobile.x.com/*
  10. // @match https://twitter.com/*
  11. // @match https://mobile.twitter.com/*
  12. // @icon https://www.google.com/s2/favicons?domain=twitter.com
  13. // @grant none
  14. // @supportURL https://github.com/lucahammer/tweetXer/issues
  15. // ==/UserScript==
  16.  
  17. (function () {
  18. var TweetsXer = {
  19. TweetCount: 0,
  20. dId: "exportUpload",
  21. tIds: [],
  22. tId: "",
  23. ratelimitreset: 0,
  24. more: '[data-testid="tweet"] [data-testid="caret"]',
  25. skip: 0,
  26. total: 0,
  27. dCount: 0,
  28. lastHeaders: {},
  29. deleteURL: '/i/api/graphql/VaenaVgh5q5ih7kvyVjgtg/DeleteTweet',
  30. unfavURL: '/i/api/graphql/ZYKSe-w7KEslx3JhSIk5LA/UnfavoriteTweet',
  31. username: '',
  32. action: '',
  33. bookmarksURL: '/i/api/graphql/L7vvM2UluPgWOW4GDvWyvw/Bookmarks?',
  34. bookmarks: [],
  35. bookmarksNext: '',
  36. baseUrl: 'https://x.com',
  37.  
  38. async init() {
  39. this.initXHR()
  40. this.baseUrl = 'https://' + window.location.hostname
  41. this.createUploadForm()
  42. await this.getTweetCount()
  43. this.username = document.location.href.split('/')[3].replace('#', '')
  44. },
  45.  
  46. sleep(ms) {
  47. return new Promise((resolve) => setTimeout(resolve, ms))
  48. },
  49.  
  50. initXHR() {
  51. console.log('init xhr')
  52. if (typeof AjaxMonitoring_notfired == "undefined") { var AjaxMonitoring_notfired = false }
  53. if (!AjaxMonitoring_notfired) {
  54. AjaxMonitoring_notfired = true
  55.  
  56. var XHR_SetRequestHeaderOriginal = XMLHttpRequest.prototype.setRequestHeader
  57. XMLHttpRequest.prototype.setRequestHeader = function (a, b) {
  58. TweetsXer.lastHeaders[a] = b
  59. XHR_SetRequestHeaderOriginal.apply(this, arguments)
  60. }
  61. }
  62. },
  63.  
  64. updateTitle(text) {
  65. document.getElementById('tweetsXer_title').textContent = text
  66. },
  67.  
  68. updateInfo(text) {
  69. document.getElementById("info").textContent = text
  70. },
  71.  
  72. createProgressBar() {
  73. let progressbar = document.createElement("progress")
  74. progressbar.setAttribute('id', "progressbar")
  75. progressbar.setAttribute('value', this.dCount)
  76. progressbar.setAttribute('max', this.total)
  77. progressbar.setAttribute('style', 'width:100%')
  78. document.getElementById(this.dId).appendChild(progressbar)
  79. },
  80.  
  81. updateProgressBar(verb = 'deleted') {
  82. document.getElementById('progressbar').setAttribute('value', this.dCount)
  83. this.updateInfo(`${this.dCount} ${verb}`)
  84. },
  85.  
  86. processFile() {
  87. let tn = document.getElementById(`${TweetsXer.dId}_file`)
  88. if (tn.files && tn.files[0]) {
  89. let fr = new FileReader()
  90. fr.onloadend = function (evt) {
  91. // window.YTD.tweet_headers.part0
  92. // window.YTD.tweets.part0
  93. // window.YTD.like.part0
  94. let cutpoint = evt.target.result.indexOf('= ')
  95. let filestart = evt.target.result.slice(0, cutpoint)
  96. let json = JSON.parse(evt.target.result.slice(cutpoint + 1))
  97.  
  98. if (filestart.includes('.tweet_headers.')) {
  99. console.log('File contains Tweets.')
  100. TweetsXer.action = 'untweet'
  101. TweetsXer.tIds = json.map((x) => x.tweet.tweet_id)
  102. } else if (filestart.includes('.tweets.') || filestart.includes('.tweet.')) {
  103. console.log('File contains Tweets.')
  104. TweetsXer.action = 'untweet'
  105. TweetsXer.tIds = json.map((x) => x.tweet.id_str)
  106. } else if (filestart.includes('.like.')) {
  107. console.log('File contains Favs.')
  108. TweetsXer.action = 'unfav'
  109. TweetsXer.tIds = json.map((x) => x.like.tweetId)
  110. } else {
  111. console.log('File content not recognized. Please use a file from the Twitter data export.')
  112. }
  113.  
  114. TweetsXer.total = TweetsXer.tIds.length
  115. document.getElementById(`${TweetsXer.dId}_file`).remove()
  116. TweetsXer.createProgressBar()
  117.  
  118. TweetsXer.skip = document.getElementById('skipCount').value
  119.  
  120. if (TweetsXer.action == 'untweet') {
  121. if (TweetsXer.skip == 0) {
  122. // If there is no amount set to skip, automatically try to skip the amount
  123. // that has been deleted already. Difference of Tweeets in file to count on profile
  124. // 5% tolerance to prevent skipping too much
  125. TweetsXer.skip = TweetsXer.total - TweetsXer.TweetCount - parseInt(TweetsXer.total / 20)
  126. TweetsXer.skip = Math.max(0, TweetsXer.skip)
  127. }
  128. console.log(`Skipping oldest ${TweetsXer.skip} Tweets. Use advanced options to manually set how many to skip. Set 1 to prevent the automatic calculation.`)
  129. TweetsXer.tIds.reverse()
  130. TweetsXer.tIds = TweetsXer.tIds.slice(TweetsXer.skip)
  131. TweetsXer.dCount = TweetsXer.skip
  132. TweetsXer.tIds.reverse()
  133. TweetsXer.updateTitle(`TweetXer: Deleting ${TweetsXer.total} Tweets`)
  134.  
  135. TweetsXer.deleteTweets()
  136. } else if (TweetsXer.action == 'unfav') {
  137. console.log(`Skipping oldest ${TweetsXer.skip} Tweets`)
  138. TweetsXer.tIds = TweetsXer.tIds.slice(TweetsXer.skip)
  139. TweetsXer.dCount = TweetsXer.skip
  140. TweetsXer.tIds.reverse()
  141. TweetsXer.updateTitle(`TweetXer: Deleting ${TweetsXer.total} Favs`)
  142. TweetsXer.deleteFavs()
  143. } else {
  144. TweetsXer.updateTitle(`TweetXer: Please try a different file`)
  145. }
  146.  
  147. }
  148. fr.readAsText(tn.files[0])
  149. }
  150. },
  151.  
  152. createUploadForm() {
  153. var h2_class = document.querySelectorAll("h2")[1]?.getAttribute("class") || ""
  154. var div = document.createElement("div")
  155. div.id = this.dId
  156. if (document.getElementById(this.dId)) { document.getElementById(this.dId).remove() }
  157. 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>
  158. <div style="color:black">
  159. <h2 class="${h2_class}" id="tweetsXer_title">TweetXer</h2>
  160. <p id="info">Select your tweet-headers.js from your Twitter Data Export to start the deletion of all your Tweets. </p>
  161. <p id="start">
  162. <input type="file" value="" id="${this.dId}_file" />
  163. <a style="color:blue" href="#" id="toggleAdvanced">Advanced Options</a>
  164. <div id="advanced" style="display:none">
  165. <label for="skipCount">Enter how many Tweets to skip before selecting a file. If 0, the script will try to automatically detect how many Tweets to skip by calcualting the difference between Tweets in the file and on the profile.</label>
  166. <input id="skipCount" type="number" value="0" />
  167. <p>To delete your Favs (aka Likes), select your like.js file. Unfaving is limited by X Corp to 500 unfavs per 15 minutes.</p>
  168. <p><strong>Export bookmarks</strong><br>
  169. Bookmarks are not included in the official data export. You can export them here.
  170. <input id="exportBookmarks" type="button" value="Export Bookmarks" />
  171. </p>
  172. <p><strong>No tweet-headers.js?</strong><br>
  173. If you are unable to get your data export, you can use the following option.<br>
  174. This option is much slower and less reliable. It can remove at most 4000 Tweets per hour.<br>
  175. <input id="slowDelete" type="button" value="Slow delete without file" />
  176. </p>
  177. <p><strong>Unfollow everyone</strong><br>
  178. It's time to let go. This will unfollow everyone you follow.<br>
  179. <input id="unfollowEveryone" type="button" value="Unfollow everyone" />
  180. </p>
  181. <p><a id="removeTweetXer" style="color:blue" href="#">Remove TweetXer</a></p>
  182. </div>
  183. </p>
  184. </div>
  185. `
  186. document.body.insertBefore(div, document.body.firstChild)
  187. document.getElementById("toggleAdvanced").addEventListener("click", (() => {
  188. let adv = document.getElementById('advanced')
  189. if (adv.style.display == 'none') {
  190. adv.style.display = 'block'
  191. } else {
  192. adv.style.display = 'none'
  193. }
  194. }))
  195. document.getElementById(`${this.dId}_file`).addEventListener("change", this.processFile, false)
  196. document.getElementById("exportBookmarks").addEventListener("click", this.exportBookmarks, false)
  197. document.getElementById("slowDelete").addEventListener("click", this.slowDelete, false)
  198. document.getElementById("unfollowEveryone").addEventListener("click", this.unfollow, false)
  199. document.getElementById("removeTweetXer").addEventListener("click", this.removeTweetXer, false)
  200.  
  201. },
  202.  
  203. async exportBookmarks() {
  204. TweetsXer.updateTitle('TweetXer: Exporting bookmarks')
  205. while (!('authorization' in TweetsXer.lastHeaders)) {
  206. await TweetsXer.sleep(1000)
  207. }
  208. let variables = ''
  209. while (TweetsXer.bookmarksNext.length > 0 || TweetsXer.bookmarks.length == 0) {
  210. if (TweetsXer.bookmarksNext.length > 0) {
  211. variables = `{"count":20,"cursor":"${TweetsXer.bookmarksNext}","includePromotedContent":true}`
  212. } else variables = '{"count":20,"includePromotedContent":false}'
  213. let response = await fetch(TweetsXer.baseUrl + TweetsXer.bookmarksURL + new URLSearchParams({
  214. variables: variables,
  215. features: '{"graphql_timeline_v2_bookmark_timeline":true,"rweb_tipjar_consumption_enabled":true,"responsive_web_graphql_exclude_directive_enabled":true,"verified_phone_label_enabled":false,"creator_subscriptions_tweet_preview_api_enabled":true,"responsive_web_graphql_timeline_navigation_enabled":true,"responsive_web_graphql_skip_user_profile_image_extensions_enabled":false,"communities_web_enable_tweet_community_results_fetch":true,"c9s_tweet_anatomy_moderator_badge_enabled":true,"articles_preview_enabled":true,"responsive_web_edit_tweet_api_enabled":true,"graphql_is_translatable_rweb_tweet_is_translatable_enabled":true,"view_counts_everywhere_api_enabled":true,"longform_notetweets_consumption_enabled":true,"responsive_web_twitter_article_tweet_consumption_enabled":true,"tweet_awards_web_tipping_enabled":false,"creator_subscriptions_quote_tweet_preview_enabled":false,"freedom_of_speech_not_reach_fetch_enabled":true,"standardized_nudges_misinfo":true,"tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled":true,"rweb_video_timestamps_enabled":true,"longform_notetweets_rich_text_read_enabled":true,"longform_notetweets_inline_media_enabled":true,"responsive_web_enhance_cards_enabled":false}'
  216. }), {
  217. "headers": {
  218. "accept": "*/*",
  219. "accept-language": 'en-US,en;q=0.5',
  220. "authorization": TweetsXer.lastHeaders.authorization,
  221. "content-type": "application/json",
  222. "sec-fetch-dest": "empty",
  223. "sec-fetch-mode": "cors",
  224. "sec-fetch-site": "same-origin",
  225. "x-client-transaction-id": TweetsXer.lastHeaders['X-Client-Transaction-Id'],
  226. "x-client-uuid": TweetsXer.lastHeaders['x-client-uuid'],
  227. "x-csrf-token": TweetsXer.lastHeaders['x-csrf-token'],
  228. "x-twitter-active-user": "yes",
  229. "x-twitter-auth-type": "OAuth2Session",
  230. "x-twitter-client-language": 'en'
  231. },
  232. "referrer": `${TweetsXer.baseUrl}/i/bookmarks`,
  233. "referrerPolicy": "strict-origin-when-cross-origin",
  234. "method": "GET",
  235. "mode": "cors",
  236. "credentials": "include"
  237. })
  238.  
  239. if (response.status == 200) {
  240. let data = await response.json()
  241. data.data.bookmark_timeline_v2.timeline.instructions[0].entries.forEach((item) => {
  242.  
  243. if (item.entryId.includes('tweet')) {
  244. TweetsXer.dCount++
  245. TweetsXer.bookmarks.push(item.content.itemContent.tweet_results.result)
  246. } else if (item.entryId.includes('cursor-bottom')) {
  247. if (TweetsXer.bookmarksNext != item.content.value) {
  248. TweetsXer.bookmarksNext = item.content.value
  249. } else {
  250. TweetsXer.bookmarksNext = ''
  251. }
  252. }
  253. })
  254. //document.getElementById('progressbar').setAttribute('value', TweetsXer.dCount)
  255. TweetsXer.updateInfo(`${TweetsXer.dCount} Bookmarks collected`)
  256. } else {
  257. console.log(response)
  258. }
  259.  
  260. if (response.headers.get('x-rate-limit-remaining') < 1) {
  261. console.log('rate limit hit')
  262. let ratelimitreset = response.headers.get('x-rate-limit-reset')
  263. let sleeptime = ratelimitreset - Math.floor(Date.now() / 1000)
  264. while (sleeptime > 0) {
  265. sleeptime = ratelimitreset - Math.floor(Date.now() / 1000)
  266. TweetsXer.updateInfo(`Ratelimited. Waiting ${sleeptime} seconds. ${TweetsXer.dCount} deleted.`)
  267. await TweetsXer.sleep(1000)
  268. }
  269. }
  270. }
  271. let download = new Blob([JSON.stringify(TweetsXer.bookmarks)], {
  272. type: 'text/plain'
  273. })
  274. let bookmarksDownload = document.createElement("a")
  275. bookmarksDownload.id = 'bookmarksDownload'
  276. bookmarksDownload.innerText = 'Download bookmarks'
  277. bookmarksDownload.href = window.URL.createObjectURL(download)
  278. bookmarksDownload.download = 'twitter-bookmarks.json'
  279. document.getElementById('advanced').appendChild(bookmarksDownload)
  280. TweetsXer.updateTitle('TweetXer')
  281. },
  282.  
  283. async deleteFavs() {
  284. TweetsXer.updateTitle('TweetXer: Deleting Favs')
  285. // 500 unfavs per 15 Minutes
  286. // x-rate-limit-remaining
  287. // x-rate-limit-reset
  288. while (!('authorization' in this.lastHeaders)) {
  289. await TweetsXer.sleep(1000)
  290. }
  291.  
  292. while (this.tIds.length > 0) {
  293. this.tId = this.tIds.pop()
  294. let response = await fetch(this.baseUrl + this.unfavURL, {
  295. "headers": {
  296. "accept": "*/*",
  297. "accept-language": 'en-US,en;q=0.5',
  298. "authorization": this.lastHeaders.authorization,
  299. "content-type": "application/json",
  300. "sec-fetch-dest": "empty",
  301. "sec-fetch-mode": "cors",
  302. "sec-fetch-site": "same-origin",
  303. "x-client-transaction-id": this.lastHeaders['X-Client-Transaction-Id'],
  304. "x-client-uuid": this.lastHeaders['x-client-uuid'],
  305. "x-csrf-token": this.lastHeaders['x-csrf-token'],
  306. "x-twitter-active-user": "yes",
  307. "x-twitter-auth-type": "OAuth2Session",
  308. "x-twitter-client-language": 'en'
  309. },
  310. "referrer": `${TweetsXer.baseUrl}/${this.username}/likes`,
  311. "referrerPolicy": "strict-origin-when-cross-origin",
  312. "body": `{\"variables\":{\"tweet_id\":\"${this.tId}\"},\"queryId\":\"${this.baseUrl + this.unfavURL.split('/')[6]}\"}`,
  313. "method": "POST",
  314. "mode": "cors",
  315. "credentials": "include"
  316. })
  317.  
  318. if (response.status == 200) {
  319. TweetsXer.dCount++
  320. TweetsXer.updateProgressBar()
  321. } else {
  322. console.log(response)
  323. }
  324.  
  325. if (response.headers.get('x-rate-limit-remaining') < 1) {
  326. console.log('rate limit hit')
  327. let ratelimitreset = response.headers.get('x-rate-limit-reset')
  328. let sleeptime = ratelimitreset - Math.floor(Date.now() / 1000)
  329. while (sleeptime > 0) {
  330. sleeptime = ratelimitreset - Math.floor(Date.now() / 1000)
  331. TweetsXer.updateInfo(`Ratelimited. Waiting ${sleeptime} seconds. ${TweetsXer.dCount} deleted.`)
  332. await TweetsXer.sleep(1000)
  333. }
  334. }
  335. }
  336. TweetsXer.updateTitle('TweetXer')
  337. },
  338.  
  339. async deleteTweets() {
  340. while (!('authorization' in this.lastHeaders)) {
  341. await TweetsXer.sleep(1000)
  342. TweetsXer.updateInfo('Waiting for auth. If this takes more than 10 seconds, try a different browser or use "slow delete without file" under Advanced options.')
  343. }
  344.  
  345. while (this.tIds.length > 0) {
  346. this.tId = this.tIds.pop()
  347. try {
  348. let response = await fetch(this.baseUrl + this.deleteURL, {
  349. "headers": {
  350. "accept": "*/*",
  351. "accept-language": 'en-US,en;q=0.5',
  352. "authorization": this.lastHeaders.authorization,
  353. "content-type": "application/json",
  354. "sec-fetch-dest": "empty",
  355. "sec-fetch-mode": "cors",
  356. "sec-fetch-site": "same-origin",
  357. "x-client-transaction-id": this.lastHeaders['X-Client-Transaction-Id'],
  358. "x-client-uuid": this.lastHeaders['x-client-uuid'],
  359. "x-csrf-token": this.lastHeaders['x-csrf-token'],
  360. "x-twitter-active-user": "yes",
  361. "x-twitter-auth-type": "OAuth2Session",
  362. "x-twitter-client-language": 'en'
  363. },
  364. "referrer": `${TweetsXer.baseUrl}/${this.username}/with_replies`,
  365. "referrerPolicy": "strict-origin-when-cross-origin",
  366. "body": `{\"variables\":{\"tweet_id\":\"${this.tId}\",\"dark_request\":false},\"queryId\":\"${this.baseUrl + this.deleteURL.split('/')[6]}\"}`,
  367. "method": "POST",
  368. "mode": "cors",
  369. "credentials": "include",
  370. "signal": AbortSignal.timeout(5000)
  371. })
  372. if (response.status == 200) {
  373. TweetsXer.dCount++
  374. TweetsXer.updateProgressBar()
  375. }
  376. else if (response.status == 429) {
  377. this.tIds.push(this.tId)
  378. console.log('Received status code 429. Waiting for 1 second before trying again.')
  379. await TweetsXer.sleep(1000)
  380. }
  381. else {
  382. console.log(response)
  383. }
  384.  
  385. } catch (error) {
  386. if (error.Name === 'AbortError') {
  387. this.tIds.push(this.tId)
  388. console.log('Request timeout.')
  389. let sleeptime = 15
  390. while (sleeptime > 0) {
  391. sleeptime--
  392. TweetsXer.updateInfo(`Ratelimited. Waiting ${sleeptime} seconds. ${TweetsXer.dCount} deleted.`)
  393. await TweetsXer.sleep(1000)
  394. }
  395. }
  396. }
  397. }
  398. },
  399.  
  400. async getTweetCount() {
  401. await waitForElemToExist('header')
  402. await TweetsXer.sleep(1000)
  403. try {
  404. document.querySelector('[data-testid="AppTabBar_Profile_Link"]').click()
  405. } catch (error) {
  406. if (document.querySelector('[aria-label="Back"]')) {
  407. document.querySelector('[aria-label="Back"]').click()
  408. await TweetsXer.sleep(1000)
  409. }
  410.  
  411. if (document.querySelector('[data-testid="app-bar-back"]')) {
  412. document.querySelector('[data-testid="app-bar-back"]').click()
  413. await TweetsXer.sleep(1000)
  414. }
  415. document.querySelector('[data-testid="DashButton_ProfileIcon_Link"]').click()
  416. await TweetsXer.sleep(1000)
  417. document.querySelector('[data-testid="AppTabBar_Profile_Link"]').click()
  418. }
  419. await waitForElemToExist('[data-testid="UserName"]')
  420. await TweetsXer.sleep(1000)
  421.  
  422. try {
  423. TweetsXer.TweetCount = document.querySelector('[data-testid="primaryColumn"]>div>div>div')
  424. .textContent.match(/((\d|,|\.|K)+) (\w+)$/)[1]
  425. .replace(/\.(\d+)K/, '$1'.padEnd(4, '0'))
  426. .replace('K', '000')
  427. .replace(',', '')
  428. } catch (error) {
  429. try {
  430. TweetsXer.TweetCount = document.querySelector('[data-testid="TopNavBar"]>div>div')
  431. .textContent.match(/((\d|,|\.|K)+) (\w+)$/)[1]
  432. .replace(/\.(\d+)K/, '$1'.padEnd(4, '0'))
  433. .replace('K', '000')
  434. .replace(',', '')
  435. }
  436. catch (error) {
  437. console.log("Wasn't able to find Tweet count on profile. Setting it to 1 million.")
  438. TweetsXer.TweetCount = 1000000 // prevents Tweets from being skipped because of tweet count of 0
  439. }
  440. }
  441. console.log(TweetsXer.TweetCount + " Tweets on profile.")
  442. console.log("You can close the console now to reduce the memory usage.")
  443. console.log("Reopen the console if there are issues to see if an error shows up.")
  444. },
  445.  
  446. async slowDelete() {
  447. //document.getElementById("toggleAdvanced").click()
  448. document.getElementById('start').remove()
  449. TweetsXer.total = TweetsXer.TweetCount
  450. TweetsXer.createProgressBar()
  451.  
  452. document.querySelectorAll('[data-testid="ScrollSnap-List"] a')[1].click()
  453. await TweetsXer.sleep(2000)
  454.  
  455. let unretweet, confirmURT, caret, menu, confirmation
  456.  
  457. const more = '[data-testid="tweet"] [data-testid="caret"]'
  458. while (document.querySelectorAll(more).length > 0) {
  459.  
  460. // give the Tweets a chance to load; increase/decrease if necessary
  461. // afaik the limit is 50 requests per minute
  462. await TweetsXer.sleep(1200)
  463.  
  464. // hide recommended profiles and stuff
  465. document.querySelectorAll('section [data-testid="cellInnerDiv"]>div>div>div').forEach(x => x.remove())
  466. document.querySelectorAll('section [data-testid="cellInnerDiv"]>div>div>[role="link"]').forEach(x => x.remove())
  467. document.querySelector(more).scrollIntoView({
  468. 'behavior': 'smooth'
  469. })
  470.  
  471. // if it is a Retweet, unretweet it
  472. unretweet = document.querySelector('[data-testid="unretweet"]')
  473. if (unretweet) {
  474. unretweet.click()
  475. confirmURT = await waitForElemToExist('[data-testid="unretweetConfirm"]')
  476. confirmURT.click()
  477. }
  478.  
  479. // delete Tweet
  480. else {
  481. caret = await waitForElemToExist(more)
  482. caret.click()
  483.  
  484.  
  485. menu = await waitForElemToExist('[role="menuitem"]')
  486. if (menu.textContent.includes('@')) {
  487. // don't unfollow people (because their Tweet is the reply tab)
  488. caret.click()
  489. document.querySelector('[data-testid="tweet"]').remove()
  490. } else {
  491. menu.click()
  492. confirmation = await waitForElemToExist('[data-testid="confirmationSheetConfirm"]')
  493. if (confirmation) confirmation.click()
  494. }
  495. }
  496.  
  497. TweetsXer.dCount++
  498. TweetsXer.updateProgressBar()
  499.  
  500. // print to the console how many Tweets already got deleted
  501. // Change the 100 to how often you want an update.
  502. // 10 for every 10th Tweet, 1 for every Tweet, 100 for every 100th Tweet
  503. if (TweetsXer.dCount % 100 == 0) console.log(`${new Date().toUTCString()} Deleted ${TweetsXer.dCount} Tweets`)
  504.  
  505. }
  506.  
  507. console.log('No Tweets left. Please reload to confirm.')
  508. },
  509.  
  510. async unfollow() {
  511. //document.getElementById("toggleAdvanced").click()
  512. let unfollowCount = 0
  513. let next_unfollow, menu
  514.  
  515. document.querySelector('[href$="/following"]').click()
  516. await TweetsXer.sleep(1200)
  517.  
  518. const accounts = '[data-testid="UserCell"]'
  519. while (document.querySelectorAll('[data-testid="UserCell"] [data-testid$="-unfollow"]').length > 0) {
  520. next_unfollow = document.querySelectorAll(accounts)[0]
  521. next_unfollow.scrollIntoView({
  522. 'behavior': 'smooth'
  523. })
  524.  
  525. next_unfollow.querySelector('[data-testid$="-unfollow"]').click()
  526. menu = await waitForElemToExist('[data-testid="confirmationSheetConfirm"]')
  527. menu.click()
  528. next_unfollow.remove()
  529. unfollowCount++
  530. if (unfollowCount % 10 == 0) console.log(`${new Date().toUTCString()} Unfollowed ${unfollowCount} accounts`)
  531. await TweetsXer.sleep(Math.floor(Math.random() * 200))
  532. }
  533.  
  534. console.log('No accounts left. Please reload to confirm.')
  535. },
  536. removeTweetXer() {
  537. document.getElementById('exportUpload').remove()
  538. }
  539. }
  540.  
  541. const waitForElemToExist = async (selector) => {
  542. return new Promise(resolve => {
  543. if (document.querySelector(selector)) {
  544. return resolve(document.querySelector(selector))
  545. }
  546.  
  547. const observer = new MutationObserver(() => {
  548. if (document.querySelector(selector)) {
  549. resolve(document.querySelector(selector))
  550. observer.disconnect()
  551. }
  552. })
  553.  
  554. observer.observe(document.body, {
  555. subtree: true,
  556. childList: true,
  557. })
  558. })
  559. }
  560.  
  561. TweetsXer.init()
  562. })()