油猴开发列子

// ==UserScript==
// @name        New script telegram.org
// @namespace   Violentmonkey Scripts
// @match       https://web.telegram.org/k/*
// @grant       none
// @version     1.0
// @author      -
// @description 2023/12/30 21:29:21
// ==/UserScript==


(function () {
   console.log("天行健,君子以自强不息!!!")
   const imgList1 = document.getElementsByClassName('sidebar-header can-have-forum');
    console.log(imgList1)
    const element = imgList1[0];
    // 1.创建按钮元素
    const button = document.createElement('button');
    button.id = 'diaaaav';  // 设置按钮的id
    button.textContent = '点击我';
    // 将按钮追加到当前元素的子节点中
    element.appendChild(button);

    // 点击时候操作2.
    document.getElementById('diaaaav').addEventListener('click', function() {
            // 获取整个网页的所有 img 标签元素
            const divimgList = document.querySelectorAll('div[class="grid-item media-container search-super-item"]');

                // 模拟点击每个 img 元素
              // 创建一个点击事件
              var clickEvent = new MouseEvent('click', {
                  bubbles: true,
                  cancelable: true,
                  view: window
              });
             var clickEvent2 = new MouseEvent('click', {
                  bubbles: true,
                  cancelable: true,
                  view: window
              });
            //遍历 divimgList,输出每个图片的 src 地址
            // divimgList.forEach(function(imgp, index) {
      console.log("总共:-------",divimgList.length)
            for (let index = 0; index < divimgList.length; index++) {
              sleep(10).then(() => {
                  try {
                    //imgp=divimgList[0]
                      imgp=divimgList[index]
                    //获取值
                    const dataMidValue = imgp ? imgp.getAttribute('data-mid') : null;
                   //获取img元素
                    const img = imgp.querySelector('img');
                    //给img元素加一个自动点击事件,在获取video标签元素下载
                    //console.log(' src:', dataMidValue,img.src);
                    // 判断同级前是否包含指定的 class
                  const hasVideoTimeClass = img && img.previousElementSibling && img.previousElementSibling.tagName === 'SPAN'
                              && img.previousElementSibling.classList.contains('video-time');
                    //是视频-跳过,视频下载是一段段的,不得行下载
                    if(hasVideoTimeClass){
                     /* img.dispatchEvent(clickEvent);
                      setTimeout(() => {
                        // 这里的代码会在300毫秒后执行
                        // 在这里执行你希望的操作,比如获取 video 标签元素
                        const videoElement = document.querySelector('video[data-ckin="default"]');
                        if(videoElement){
                          console.log("000000000",videoElement)
                          try{
                            //关闭窗口操作---获取父级元素
                            const parentElement = document.querySelector('.media-viewer-topbar.media-viewer-appear');
                            // 获取最里面的 <span> 元素
                            const innerSpanElement = parentElement.querySelector('span');
                            //关闭窗口
                            innerSpanElement.dispatchEvent(clickEvent2);
                          }catch (error) {
                            //关闭窗口操作---获取父级元素
                            const parentElement = document.querySelector('.media-viewer-topbar.media-viewer-appear');
                            // 获取最里面的 <span> 元素
                            const innerSpanElement = parentElement.querySelector('span');
                            //关闭窗口
                            innerSpanElement.dispatchEvent(clickEvent2);
                          }

                          console.log('Video ' , videoElement.src);
                          downloadVideo(videoElement.src,dataMidValue);

                        }
                      }, 1000);*/
                    }else{
                      //图片直接下载
                      setTimeout(() => {
                           downloadBlob(img.src,dataMidValue);
                      }, 1000);
                    }
              } catch (error) {
                /*//关闭窗口操作---获取父级元素
                const parentElement = document.querySelector('.media-viewer-topbar.media-viewer-appear');
                // 获取最里面的 <span> 元素
                const innerSpanElement = parentElement.querySelector('span');
                //关闭窗口
                innerSpanElement.dispatchEvent(clickEvent2);*/
              }
});

           }

            // 模拟点击每个 img 元素
            //imgList[0].dispatchEvent(clickEvent);



        // 使用例子
      //var blobUrl = "blob:https://web.telegram.org/30d02334-880b-4036-9399-03e63da1e71d";
      //console.log(imgList[0])
       // downloadBlob(imgList[0].src);
    });
//睡眠函数
// 等待 10 秒钟的函数
function sleep(seconds) {
  return new Promise(resolve => setTimeout(resolve, seconds));
}


function downloadBlob(blobUrl,fileName) {

    // 创建一个a元素
    var link = document.createElement('a');

    // 设置a元素的href属性为blob URL
    link.href = blobUrl;

    // 设置download属性为文件名
    link.download = fileName || 'downloadedFile';

    // 模拟点击链接来触发下载
    link.click();
}

function downloadVideo(videoUrl, fileName) {
  // 发送 fetch 请求
  fetch(videoUrl)
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      return response.blob(); // 将响应转换为 Blob 对象
    })
    .then(blob => {
      // 创建一个链接元素
      const link = document.createElement('a');

      // 创建一个包含 Blob 数据的 URL
      const blobUrl = URL.createObjectURL(blob);

      // 设置链接的 href 属性为 Blob URL
      link.href = blobUrl;

      // 设置下载属性为文件名
      link.download = fileName;

      // 模拟点击链接来触发下载
      link.click();

      // 释放 Blob URL
      URL.revokeObjectURL(blobUrl);
    })
    .catch(error => {
      console.error('Error:', error);
    });
}


})(); //(function(){})() 表示该函数立即执行

第二个

// ==UserScript==
// @name        New script telegram.org222
// @namespace   Violentmonkey Scripts222
// @match       https://web.telegram.org/k/*
// @grant       none
// @version     1.0
// @author      -
// @description 2023/12/31 14:22:48
// ==/UserScript==

(function () {
let myArray =['4294975711', '4294978126', '4294979298', '4294979300']
  console.log("天行健,君子以自强不息!!!")
  //日志打印
  const logger = {
  info: (message, fileName = null) => {
    console.log(
      `[Tel Download] ${fileName ? `${fileName}: ` : ""}${message}`
    );
  },
  error: (message, fileName = null) => {
    console.error(
      `[Tel Download] ${fileName ? `${fileName}: ` : ""}${message}`
    );
  },
  };
  const contentRangeRegex = /^bytes (\d+)-(\d+)\/(\d+)$/;
  const REFRESH_DELAY = 500;



   const imgList1 = document.getElementsByClassName('sidebar-header can-have-forum');
   console.log(imgList1)
   const element = imgList1[0];
    // 1.创建按钮元素
    const button = document.createElement('button');
    button.id = 'diaaaav';  // 设置按钮的id
    button.textContent = '点击我';
    // 将按钮追加到当前元素的子节点中
    element.appendChild(button);



    // 点击时候操作2.
    document.getElementById('diaaaav').addEventListener('click', function() {
            // 获取整个网页的所有 img 标签元素
            const divimgList = document.querySelectorAll('div[class="grid-item media-container search-super-item"]');
            //遍历 divimgList,输出每个图片的 src 地址
            // divimgList.forEach(function(imgp, index) {
            console.log("总共:-------",divimgList.length)
            // 调用异步函数
             processImages(divimgList);

    });

//睡眠函数
// 等待 10 秒钟的函数
function sleep(seconds) {
  return new Promise(resolve => setTimeout(resolve, seconds));
}
function saveTextToFile(text, fileName) {
  // 创建一个Blob对象
  const blob = new Blob([text], { type: 'text/plain' });

  // 创建一个下载链接
  const downloadLink = document.createElement('a');

  // 设置下载链接的href属性为Blob对象的URL
  downloadLink.href = URL.createObjectURL(blob);

  // 设置下载链接的下载属性为文件名
  downloadLink.download = fileName || 'file.txt'; // 默认文件名为file.txt

  // 将下载链接添加到文档中
  document.body.appendChild(downloadLink);

  // 模拟点击下载链接
  downloadLink.click();

  // 移除下载链接
  document.body.removeChild(downloadLink);
}

// 修改循环为异步函数
async function processImages(divimgList) {
      var txt="";
      var txt2="";
      for (let index = 0; index < divimgList.length; index++) {
        try {
        // 创建一个点击事件
        const clickEvent = new MouseEvent('click', {
            bubbles: true,
            cancelable: true,
            view: window
        });

          //imgp=divimgList[0]
          imgp = divimgList[index];
          //获取值
          const dataMidValue = imgp ? imgp.getAttribute('data-mid') : null;
            if(myArray.includes(dataMidValue)){
               continue;
             }
          //获取img元素
          const img = imgp.querySelector('img');
          // 判断同级前是否包含指定的 class
          const hasVideoTimeClass = img && img.previousElementSibling && img.previousElementSibling.tagName === 'SPAN'
            && img.previousElementSibling.classList.contains('video-time');
          //是视频-跳过,视频下载是一段段的,不得行下载
          if (hasVideoTimeClass) {
            // 跳过当前迭代,进入下一次循环
            img.dispatchEvent(clickEvent);
            // 这里的代码会在300毫秒后执行
            await sleep(300); //等待
            // 在这里执行你希望的操作,比如获取 video 标签元素
            const videoElement = document.querySelector('video[data-ckin="default"]');
            if(videoElement&&videoElement.src){
              console.log("000000000",videoElement)
              console.log('Video 11111111111' , videoElement.src);
              txt+=videoElement.src+"====="+dataMidValue+"-----"
            }
            //
            //下载
            //tel_download_video(videoElement.src,dataMidValue);

            // 调用下载函数
            // await tel_download_video(videoElement.src, dataMidValue);

            await sleep(300); //等待
               try{
                  //关闭窗口操作---获取父级元素
                const parentElement = document.querySelector('.media-viewer-topbar.media-viewer-appear');
                // 获取最里面的 <span> 元素
                const innerSpanElement = parentElement.querySelector('span');
                //关闭窗口
                innerSpanElement.dispatchEvent(clickEvent);
              }catch(error){

              }

          }else{
            txt2+=img.src+"====="+dataMidValue+"-----"
          }
        } catch (error) {
          logger.error('Error:', error);
          try{
              //关闭窗口操作---获取父级元素
            const parentElement = document.querySelector('.media-viewer-topbar.media-viewer-appear');
            // 获取最里面的 <span> 元素
            const innerSpanElement = parentElement.querySelector('span');
            //关闭窗口
            innerSpanElement.dispatchEvent(clickEvent);
          }catch(error){
              // 如果有异常,可以在这里处理
             continue;
          }
          // 如果有异常,可以在这里处理
          continue;
        }
      }
  saveTextToFile(txt, "a.txt")
    saveTextToFile(txt2, "a2.txt")

}





})(); //(function(){})() 表示该函数立即执行

第3个

// ==UserScript==
// @name        New script telegram.org333
// @namespace   Violentmonkey Scripts3333
// @match       https://web.telegram.org/k/*
// @grant       none
// @version     1.0
// @author      -
// @description 2023/12/31 17:48:05
// ==/UserScript==

(function () {
  let myArray =['4294975711','4295049922', '4295049956', '4295049958', '4295049959']
    //日志打印
  const logger = {
  info: (message, fileName = null) => {
    console.log(
      `[Tel Download] ${fileName ? `${fileName}: ` : ""}${message}`
    );
  },
  error: (message, fileName = null) => {
    console.error(
      `[Tel Download] ${fileName ? `${fileName}: ` : ""}${message}`
    );
  },
  };
  const contentRangeRegex = /^bytes (\d+)-(\d+)\/(\d+)$/;
  //const REFRESH_DELAY = 500;


  const imgList1 = document.getElementsByClassName('sidebar-header can-have-forum');
  const element = imgList1[0];

  //创建一个input框和一个按钮,上传文件读取里面内容打印到控制台
  // 加一个按钮
  const button22 = document.createElement('button');
  button22.id = 'button22';  // 设置按钮的id
  button22.textContent = '点击我button22';
  // 将按钮追加到当前元素的子节点中
  element.appendChild(button22);

  // 创建一个上传文件的 input 元素
  const fileInput = document.createElement('input');
  // 设置 input 的 type 为 file
  fileInput.type = 'file';
  // 设置 input 的其他属性,例如 name、id 等
  fileInput.name = 'myFile'; // 设置文件上传的表单字段名称
  fileInput.id = 'fileInputId'; // 设置元素的 id
  // 将 input 元素添加到页面的某个容器中,例如 body
  element.appendChild(fileInput);

// 点击按钮时触发文件选择
document.getElementById('button22').addEventListener('click', function () {
    fileInput.click();
});

// 监听文件输入框的 change 事件
fileInput.addEventListener('change', handleFileSelect);
//睡眠函数
// 等待 10 秒钟的函数
function sleep(seconds) {
  return new Promise(resolve => setTimeout(resolve, seconds));
}
// 文件选择后的处理函数
 function handleFileSelect(event) {
    const selectedFile = event.target.files[0];
    if (selectedFile) {
        const reader = new FileReader();
        reader.onload = function (e) {
            const fileContent = e.target.result;
            // 在这里可以处理文件内容
            // console.log('文件内容File Content:', fileContent);
            aaa(fileContent);
        };
        // 以文本形式读取文件
        reader.readAsText(selectedFile);
    }
}
var aaatext="";

function saveTextToFile(text, fileName) {
  // 创建一个Blob对象
  const blob = new Blob([text], { type: 'text/plain' });

  // 创建一个下载链接
  const downloadLink = document.createElement('a');

  // 设置下载链接的href属性为Blob对象的URL
  downloadLink.href = URL.createObjectURL(blob);

  // 设置下载链接的下载属性为文件名
  downloadLink.download = fileName || 'file.txt'; // 默认文件名为file.txt

  // 将下载链接添加到文档中
  document.body.appendChild(downloadLink);

  // 模拟点击下载链接
  downloadLink.click();

  // 移除下载链接
  document.body.removeChild(downloadLink);
}
async function aaa(fileContent) {
  // 根据分隔符切割字符串
  const fragments = fileContent.split("-----");

  for (let index = 0; index < fragments.length; index++) {
       try{
          const a=fragments[index]
          const fragments22 = a.split("=====");
          console.log(fragments22[1],fragments22[0])
         if(myArray.includes(fragments22[0])){
           continue;
         }
          await sleep(3000); //等待
          if(fragments22[0]&&fragments22[1]){
            tel_download_video(fragments22[0],fragments22[1]);
          }
        }catch(error){
          aaatext+=fragments22[0]+"====="+fragments22[1]+"-----"
            // 如果有异常,可以在这里处理
           continue;
        }

  }
  saveTextToFile(aaatext, "a11.txt")

}

const tel_download_video =(url,fileName) => {
  const a1=url;
  const a2=fileName;

  let _blobs = [];
  let _next_offset = 0;
  let _total_size = null;
  let _file_extension = "mp4";

  fileName =fileName+ "." + _file_extension;
  // Some video src is in format:
  // 'stream/{"dcId":5,"location":{...},"size":...,"mimeType":"video/mp4","fileName":"xxxx.MP4"}'
  // try {
  //   const metadata = JSON.parse(
  //     decodeURIComponent(url.split("/")[url.split("/").length - 1])
  //   );
  //   if (metadata.fileName) {
  //     fileName = metadata.fileName;
  //   }
  // } catch (e) {
  //   // Invalid JSON string, pass extracting fileName
  // }
  logger.info(`URL: ${url}`, fileName);

  const fetchNextPart =() => {
  fetch(url, {
    method: "GET",
    headers: {
      Range: `bytes=${_next_offset}-`,
    },
    "User-Agent":
      "User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/117.0",
  })
    .then((res) => {
      if (![200, 206].includes(res.status)) {
        throw new Error("Non 200/206 response was received: " + res.status);
      }
      const mime = res.headers.get("Content-Type").split(";")[0];
      if (!mime.startsWith("video/")) {
        throw new Error("Get non video response with MIME type " + mime);
      }
      _file_extension = mime.split("/")[1];
      fileName =
        fileName.substring(0, fileName.indexOf(".") + 1) + _file_extension;

      const match = res.headers
        .get("Content-Range")
        .match(contentRangeRegex);

      const startOffset = parseInt(match[1]);
      const endOffset = parseInt(match[2]);
      const totalSize = parseInt(match[3]);

      if (startOffset !== _next_offset) {
        logger.error("Gap detected between responses.", fileName);
        logger.info("Last offset: " + _next_offset, fileName);
        logger.info("New start offset " + match[1], fileName);
        throw "Gap detected between responses.";
      }
      if (_total_size && totalSize !== _total_size) {
        logger.error("Total size differs", fileName);
        throw "Total size differs";
      }

      _next_offset = endOffset + 1;
      _total_size = totalSize;

      logger.info(
        `Get response: ${res.headers.get(
          "Content-Length"
        )} bytes data from ${res.headers.get("Content-Range")}`,
        fileName
      );
      logger.info(
        `Progress: ${((_next_offset * 100) / _total_size).toFixed(0)}%`,
        fileName
      );
      return res.blob();
    })
    .then((resBlob) => {
      _blobs.push(resBlob);
    })
    .then(() => {
      if (!_total_size) {
        throw new Error("_total_size is NULL");
      }

      if (_next_offset < _total_size) {
        fetchNextPart();
      } else {
        save();
      }
    })
    .catch((reason) => {
      logger.error(reason, fileName);
    //11111111111--------------去掉url,
      aaatext+=a1+"====="+a2+"-----11111111111--------------"
    });
};

const save =() => {
  logger.info("Finish downloading blobs", fileName);
  logger.info("Concatenating blobs and downloading...", fileName);

  const blob = new Blob(_blobs, { type: "video/mp4" });
  const blobUrl = window.URL.createObjectURL(blob);

  logger.info("Final blob size: " + blob.size + " bytes", fileName);

  const a = document.createElement("a");
  document.body.appendChild(a);
  a.href = blobUrl;
  a.download = fileName;
  a.click();
  document.body.removeChild(a);
  window.URL.revokeObjectURL(blobUrl);
  // 下载完成后继续执行后面的代码
  console.log('下载完成后继续执行Download completed.');
};
fetchNextPart();
};
})(); //(function(){})() 表示该函数立即执行
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当你想要在应用程序中监视和处理特定事件时,可以使用 `installEventFilter` 方法。下面是一个使用 `installEventFilter` 的示例代码: ```cpp #include <QCoreApplication> #include <QObject> #include <QEvent> #include <QDebug> class EventFilter : public QObject { public: bool eventFilter(QObject* watched, QEvent* event) override { if (event->type() == QEvent::KeyPress) { QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event); qDebug() << "Key press event:" << keyEvent->key(); return true; // 返回 true 表示事件已被处理 } // 返回 false 表示事件未被处理,将其传递给原始的事件接收者 return QObject::eventFilter(watched, event); } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QObject target; // 创建一个 QObject 对象作为事件接收者 EventFilter filter; // 创建一个 EventFilter 对象作为事件过滤器 target.installEventFilter(&filter); // 将事件过滤器安装到事件接收者上 target.event(QEvent(QEvent::KeyPress)); // 模拟一个按键事件 return a.exec(); } ``` 在上述示例中,我们创建了一个自定义的 `EventFilter` 类,继承自 `QObject`。在 `eventFilter` 函数中,我们检查事件的类型是否为按键事件 (`QEvent::KeyPress`),如果是,我们将打印出按下的键值,并返回 true,表示事件已被处理。如果事件不是按键事件,则将事件传递给原始的事件接收者。 在 `main` 函数中,我们创建了一个 `QObject` 对象 `target` 作为事件接收者,并创建了一个 `EventFilter` 对象 `filter` 作为事件过滤器。然后,我们使用 `installEventFilter` 方法将事件过滤器安装到事件接收者上。最后,我们通过调用 `target.event` 来模拟一个按键事件。 当运行这段代码时,如果一切正常,你将会在控制台看到类似以下的输出: ``` Key press event: 16777220 ``` 这表示按下了一个键,并打印出了对应的键值。这个例子演示了如何通过使用 `installEventFilter` 方法来监视和处理特定事件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值