如何删除所有推文

这个脚本的基础上,让 ChatGPT 改了改,适合中文界面使用,一键就能删除所有推文,方法和代码如下:

  1. 使用 Chrome 浏览器,登陆你的 X 账户
  2. 打开这个链接 https://x.com/USERNAME/with_replies ,用你的用户名替换链接里的 UASERNAME
  3. 在 Chrome 菜单里依次点击:显示-开发者-开发者工具
  4. 在开发者工具上方的栏目里选择“Console”
  5. 复制黏贴以下代码,回撤执行,等待足够长时间即可

const deleteAllTweetsAndReplies = async () => {
  const processed = new Set();
  const selectors = {
    tweet: '[data-testid="tweet"]', // 推文 & 回复
    caret: '[data-testid="caret"]',
    menuItem: '[role="menuitem"]',
    deleteConfirm: '[data-testid="confirmationSheetConfirm"]',
    unretweet: '[data-testid="unretweet"]',
    unretweetConfirm: '[data-testid="unretweetConfirm"]'
  };

  const delay = ms => {
    const jitter = ms * 0.3;
    const actual = ms + (Math.random() * jitter * 2 - jitter);
    return new Promise(resolve => setTimeout(resolve, actual));
  };

  const getButtons = () =>
    Array.from(document.querySelectorAll(${selectors.tweet} ${selectors.caret}))
      .filter(b => !processed.has(b));

  const scrollToEnd = async () => {
    window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
    await delay(2500); // 等待加载
  };

  const attemptDelete = async button => {
    try {
      processed.add(button);
      button.scrollIntoView({ behavior: 'smooth', block: 'center' });
      await delay(500);
      button.click();
      await delay(500);

      const menuItems = Array.from(document.querySelectorAll(selectors.menuItem));
      const deleteWords = ['Delete', '删除', '删除贴文']; // 中英文匹配
      const deleteOption = menuItems.find(item =>
        deleteWords.some(word => item.textContent.includes(word))
      );

      if (deleteOption) {
        deleteOption.click();
        await delay(500);
        const confirm = document.querySelector(selectors.deleteConfirm);
        if (confirm) {
          confirm.click();
          await delay(3000);
          return true;
        }
      }

      const tweet = button.closest(selectors.tweet);
      const unretweet = tweet?.querySelector(selectors.unretweet);
      if (unretweet) {
        unretweet.click();
        await delay(500);
        const confirm = document.querySelector(selectors.unretweetConfirm);
        if (confirm) {
          confirm.click();
          await delay(3000);
          return true;
        }
      }
    } catch (err) {
      console.error('Error attempting to delete/unretweet:', err);
    }
    return false;
  };

  while (true) {
    let buttons = getButtons();
    if (!buttons.length) {
      await scrollToEnd();
      buttons = getButtons();
      if (!buttons.length) break;
    }

    for (const button of buttons) {
      await attemptDelete(button);
      await delay(800); // 防风控冷却
    }
  }

  console.log('所有推文和回复已处理完毕(删除或取消转推)。');
};

deleteAllTweetsAndReplies().catch(err => console.error('脚本执行失败:', err));