Greasy Fork

Greasy Fork is available in English.

YouTube 智能广告处理器(AI规避检测+自动适应反广告拦截+自动刷新异常 v1.3)

利用AI策略自动更新规则,规避广告检测与反广告拦截机制,同时在视频播放异常时自动刷新页面。仅在观看视频时检测卡顿。

当前为 2025-06-14 提交的版本,查看 最新版本

// ==UserScript==
// @name         YouTube 智能广告处理器(AI规避检测+自动适应反广告拦截+自动刷新异常 v1.3)
// @namespace    http://tampermonkey.net/
// @version      1.3
// @description  利用AI策略自动更新规则,规避广告检测与反广告拦截机制,同时在视频播放异常时自动刷新页面。仅在观看视频时检测卡顿。
// @author       OpenAI & ChatGPT优化版
// @match        *://www.youtube.com/*
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// @connect      openkey.cloud
// @run-at       document-end
// ==/UserScript==

(function () {
  'use strict';

  const OPENKEY_API = 'https://openkey.cloud/v1/chat/completions';
  const API_KEY = 'sk-1ytLNfSpk5R34njTF6286656331c426cAeCb95E266F8D377';
  const DEBUG = true;

  let dynamicSelectors = [];
  let lastUpdate = 0;
  let lastDefendTrigger = 0;

  function log(...args) {
    if (DEBUG) console.log(...args);
  }

  function detectAdblockWarning() {
    const keywords = ['ad blocker', '广告拦截', 'looks like you\'re using'];
    const bodyText = document.body.innerText.toLowerCase();
    return keywords.some(word => bodyText.includes(word.toLowerCase()));
  }

  async function updateSelectorsViaAI(defensive = false) {
    if (!API_KEY || Date.now() - lastUpdate < 3600000 && !defensive) return;
    try {
      GM_xmlhttpRequest({
        method: 'POST',
        url: OPENKEY_API,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${API_KEY}`
        },
        data: JSON.stringify({
          model: "gpt-4o",
          messages: [{
            role: "user",
            content: defensive 
              ? "YouTube 检测到用户使用广告拦截器,提示出现广告拦截器被检测,请提供更稳妥的CSS选择器数组来隐藏广告并规避检测。返回纯 JSON 数组格式,如 ['.ytp-ad-module', ...],不要解释。"
              : "请提供用于屏蔽YouTube广告元素的CSS选择器数组,使用JSON格式返回。不要解释,仅返回形如 ['.ytp-ad-module', ...] 的数组"
          }],
          temperature: 0.3
        }),
        onload: res => {
          try {
            const data = JSON.parse(res.responseText);
            let content = data.choices[0].message.content.trim();
            content = content.replace(/```json|```/g, '').trim();
            const list = JSON.parse(content);
            if (Array.isArray(list)) {
              dynamicSelectors = list;
              GM_setValue('yt_ad_selectors', list);
              lastUpdate = Date.now();
              log(defensive ? '[AI防御模式] 规则更新成功:' : '[AI规则] 更新成功:', list);
            } else {
              log('[AI规则] AI返回非数组:', content);
            }
          } catch (e) {
            console.warn('[AI规则] 解析失败', e);
          }
        }
      });
    } catch (e) {
      console.warn('[AI规则] 请求失败', e);
    }
  }

  const defaultSelectors = [
    '.ad-showing .video-ads',
    '.ytp-ad-overlay-container',
    '.ytp-ad-player-overlay',
    '.ytp-ad-module',
    '#player-ads'
  ];

  function hideAdsSmartly() {
    const selectors = [...defaultSelectors, ...dynamicSelectors];
    selectors.forEach(sel => {
      try {
        document.querySelectorAll(sel).forEach(el => {
          el.style.opacity = '0.01';
          el.style.pointerEvents = 'none';
          el.style.position = 'absolute';
          el.style.left = '-9999px';
          el.style.top = '-9999px';
          el.style.zIndex = '0';
        });
      } catch (e) {
        log('[软隐藏异常]', e);
      }
    });
  }

  function clickSkipButton() {
    const btn = document.querySelector('.ytp-ad-skip-button');
    if (btn && btn.offsetParent !== null) {
      setTimeout(() => {
        try {
          btn.click();
          log('[智能跳过] 已跳过广告');
        } catch (e) {
          log('[跳过失败]', e);
        }
      }, 500 + Math.random() * 500);
    }
  }

  let lastAdState = false;
  function accelerateAds() {
    const video = document.querySelector('video');
    const adShowing = document.querySelector('.ad-showing') !== null;
    if (video) {
      if (adShowing) {
        video.playbackRate = 16;
        video.muted = true;
        if (!lastAdState) log('[加速] 广告中,加速播放');
      } else {
        video.playbackRate = 1;
        video.muted = false;
        if (lastAdState) log('[加速] 恢复正常播放');
      }
      lastAdState = adShowing;
    }
  }

  function detectAdDuration() {
    const video = document.querySelector('video');
    if (video && document.querySelector('.ad-showing')) {
      log('[广告时长] 当前广告时长:', video.duration.toFixed(1), '秒');
    }
  }

  // 只在观看视频页检测卡顿
  function isWatchPage() {
    return window.location.href.includes('/watch?v=');
  }

  let lastVideoTime = 0;
  let stalledCount = 0;
  const STALLED_THRESHOLD = 10;
  const CHECK_INTERVAL = 2000;

  setInterval(() => {
    if (!isWatchPage()) {
      stalledCount = 0;
      return;
    }

    const video = document.querySelector('video');
    const adShowing = document.querySelector('.ad-showing') !== null;

    if (video && !adShowing) {
      if (video.currentTime === lastVideoTime) {
        stalledCount++;
        log(`[卡顿检测] 视频未推进,卡顿计数: ${stalledCount}`);
        if (stalledCount >= STALLED_THRESHOLD) {
          log('[卡顿检测] 视频长时间卡顿,刷新页面');
          location.reload();
        }
      } else {
        stalledCount = 0;
        lastVideoTime = video.currentTime;
      }
    } else {
      stalledCount = 0;
    }
  }, CHECK_INTERVAL);

  // 每秒执行核心功能
  setInterval(() => {
    hideAdsSmartly();
    clickSkipButton();
    accelerateAds();
    detectAdDuration();

    if (detectAdblockWarning()) {
      if (Date.now() - lastDefendTrigger > 10 * 60 * 1000) {
        log('[反检测] 检测到广告拦截提示,触发AI防御更新');
        updateSelectorsViaAI(true);
        lastDefendTrigger = Date.now();
      }
    }
  }, 1000);

  // 初始化
  (function init() {
    dynamicSelectors = GM_getValue('yt_ad_selectors', []);
    updateSelectorsViaAI();
    setInterval(updateSelectorsViaAI, 3600000);
    log('[AI广告模块] 初始化完成 v1.3');
  })();
})();