TweetXer

Delete all your Tweets for free.

当前为 2024-11-23 提交的版本,查看 最新版本

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