多时间点多按钮定时自动点击

// ==UserScript==
// @name         多时间点多按钮定时自动点击
// @namespace    http://tampermonkey.net/
// @version      3.6
// @description  多任务、独立时间/选择器/坐标、启用开关、时间校验、防无限弹窗、单次刷新限制、日志隔离,自动明暗主题 + 填写帮助 + 获取鼠标坐标
// @author       You
// @match        *://*/*
// @grant        GM_registerMenuCommand
// @grant        GM_setValue
// @grant        GM_getValue
// ==/UserScript==

(function() {
    'use strict';

    // task: { enable:bool, time, selector, usePos, x, y, refreshSec, refreshed:bool }
    let taskList = GM_getValue('autoClick_taskList', [
        { enable: false, time: "09:00:00", selector: "", usePos: false, x: 100, y: 100, refreshSec: 10, refreshed: false }
    ]);
    let executedToday = GM_getValue('autoClick_executedToday', []);
    let captureCoordTaskIndex = null;

    function saveAll() {
        GM_setValue('autoClick_taskList', taskList);
        GM_setValue('autoClick_executedToday', executedToday);
    }

    function getTodayStr() {
        const d = new Date();
        const y = d.getFullYear();
        const m = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return `${y}-${m}-${day}`;
    }

    function getTaskId(idx) {
        return getTodayStr() + "_" + idx;
    }

    function isValidTime(str) {
        return /^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/.test(str);
    }

    function parseTime(timeStr) {
        const arr = timeStr.split(':').map(Number);
        return { h: arr[0], m: arr[1], s: arr[2] };
    }

    function getDiffSec(timeStr) {
        const now = new Date();
        const t = parseTime(timeStr);
        const target = new Date();
        target.setHours(t.h, t.m, t.s, 0);
        return Math.round((target - now) / 1000);
    }

    function waitElement(selector, timeout = 30000) {
        return new Promise((resolve, reject) => {
            const start = Date.now();
            const timer = setInterval(() => {
                const el = document.querySelector(selector);
                if (el) {
                    clearInterval(timer);
                    resolve(el);
                }
                if (Date.now() - start > timeout) {
                    clearInterval(timer);
                    reject(new Error("等待元素超时,未找到按钮"));
                }
            }, 300);
        });
    }

    async function runTask(task, taskIndex, isTest = false) {
        if (!task.usePos && !task.selector.trim()) {
            if (isTest) alert(`【测试】❌ 任务${taskIndex+1}:选择器为空,跳过`);
            console.log(`[定时] 任务${taskIndex+1} 选择器为空,跳过`);
            if (!isTest) {
                executedToday.push(getTaskId(taskIndex));
                saveAll();
            }
            return;
        }

        if (task.usePos) {
            const evt = new MouseEvent('click', {
                clientX: task.x,
                clientY: task.y,
                bubbles: true,
                cancelable: true
            });
            document.dispatchEvent(evt);
            if (isTest) alert(`【测试】✅ 任务${taskIndex+1} 坐标点击完成`);
            console.log(`[定时] 任务${taskIndex+1} 坐标点击执行`);
        } else {
            try {
                const el = await waitElement(task.selector);
                el.click();
                if (isTest) alert(`【测试】✅ 任务${taskIndex+1} 点击成功`);
                console.log(`[定时] 任务${taskIndex+1} 选择器点击执行`);
            } catch (err) {
                console.error(`[定时] 任务${taskIndex+1}`, err);
                if (isTest) alert(`【测试】❌ 任务${taskIndex+1}:${err.message}`);
            }
        }
        if (!isTest) {
            executedToday.push(getTaskId(taskIndex));
            saveAll();
        }
    }

    function renderPanel() {
        const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        // 明暗配色
        const bgMain = isDark ? '#1e1e1e' : '#ffffff';
        const textMain = isDark ? '#e9e9e9' : '#222222';
        const bgItem = isDark ? '#2a2a2a' : '#ffffff';
        const borderColor = isDark ? '#444444' : '#dddddd';
        const inputBg = isDark ? '#333333' : '#ffffff';
        const inputText = isDark ? '#eeeeee' : '#222222';
        const hintBg = isDark ? '#2c2c2c' : '#f7f7f7';
        const hintText = isDark ? '#bbbbbb' : '#666666';

        let taskHtml = "";
        taskList.forEach((t, i) => {
            taskHtml += `
<div class="task-item" style="border:1px solid ${borderColor};padding:12px;border-radius:8px;margin-bottom:10px;background:${bgItem};">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
        <span style="font-weight:bold;color:${textMain};">任务 ${i+1}</span>
        <label style="display:flex;align-items:center;gap:4px;font-size:13px;color:${textMain};">
            <input class="t-enable" data-idx="${i}" type="checkbox" ${t.enable ? "checked" : ""}>启用
        </label>
        <button data-del="${i}" style=" color:#ef4444;border:none;background:transparent;cursor:pointer;">删除</button>
    </div>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:8px;">
        <div>
            <label style="font-size:13px;color:${textMain};">时间 HH:mm:ss</label>
            <input class="t-time" data-idx="${i}" value="${t.time}" style="width:100%;box-sizing:border-box;padding:6px;border:1px solid ${borderColor};border-radius:6px;background:${inputBg};color:${inputText};">
        </div>
        <div>
            <label style="font-size:13px;color:${textMain};">提前刷新秒数</label>
            <input class="t-refresh" data-idx="${i}" value="${t.refreshSec}" style="width:100%;box-sizing:border-box;padding:6px;border:1px solid ${borderColor};border-radius:6px;background:${inputBg};color:${inputText};">
        </div>
    </div>
    <div style="margin-bottom:8px;">
        <label style="font-size:13px;color:${textMain};">CSS选择器</label>
        <input class="t-sel" data-idx="${i}" value="${t.selector}" style="width:100%;box-sizing:border-box;padding:6px;border:1px solid ${borderColor};border-radius:6px;background:${inputBg};color:${inputText};">
    </div>
    <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
        <label style="display:flex;align-items:center;font-size:13px;color:${textMain};">
            <input class="t-usePos" data-idx="${i}" type="checkbox" ${t.usePos ? "checked" : ""}> 坐标点击
        </label>
        <span style="font-size:13px;color:${textMain};">X:</span>
        <input class="t-x" data-idx="${i}" value="${t.x}" style="width:60px;padding:6px;border:1px solid ${borderColor};border-radius:6px;background:${inputBg};color:${inputText};">
        <span style="font-size:13px;color:${textMain};">Y:</span>
        <input class="t-y" data-idx="${i}" value="${t.y}" style="width:60px;padding:6px;border:1px solid ${borderColor};border-radius:6px;background:${inputBg};color:${inputText};">
        <button data-capture="${i}" style="padding:4px 8px;border:1px solid #22c55e;border-radius:4px;background:${isDark?'#1a2e22':'#f0fdf4'};color:${textMain};cursor:pointer;font-size:13px;">获取鼠标坐标</button>
        <button data-test="${i}" style="padding:4px 8px;border:1px solid ${borderColor};border-radius:4px;background:${inputBg};color:${textMain};cursor:pointer;font-size:13px;">测试</button>
    </div>
</div>
`;
        });

        const html = `
<div style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:999999;display:flex;align-items:center;justify-content:center;">
    <div style="background:${bgMain};padding:20px;border-radius:10px;width:540px;max-height:85vh;overflow-y:auto;box-sizing:border-box;font-family:system-ui, sans-serif;box-shadow:0 4px 20px rgba(0,0,0,0.4);">
        <h3 style="margin:0 0 14px 0;text-align:center;color:${textMain};">多任务定时点击设置</h3>
        <div style="font-size:12px;color:${hintText};background:${hintBg};padding:10px;border-radius:6px;margin-bottom:12px;line-height:1.6;">
 <b>填写帮助:</b><br>
• 时间:HH:mm:ss,例:09:00:00,每天到点执行<br>
• CSS选择器:F12开发者工具,选中按钮 → 右键【复制】→【复制selector】,优先这个;勾选【坐标点击】则直接按X/Y位置点击<br>
• 获取鼠标坐标:点按钮后,移动鼠标到目标位置,再点一下页面任意地方自动填入X/Y<br>
• 提前刷新秒数:距离目标时间还有N秒自动刷新页面;填0=不刷新<br>
• 测试按钮:立即执行一次,用来验证是否能点到,不会计入今日执行记录<br>
• 重置今日执行:清除今天已完成标记,当天可以重新跑一遍任务<br>
⚠️ 注意:脚本只在当前这个标签页生效,页面切后台/休眠会失效;坐标方式页面滚动后位置会偏移
        </div>
        <div id="taskWrap">${taskHtml}</div>
        <div style="margin:10px 0;display:flex;gap:8px;">
            <button id="addTaskBtn" style="flex:1;padding:8px;border:1px dashed #4080ff;background:${isDark?'#202b3d':'#f0f7ff'};color:${textMain};border-radius:6px;cursor:pointer;">+ 添加任务</button>
            <button id="resetExecBtn" style="padding:8px;border:1px solid #f59e0b;background:${isDark?'#383020':'#fffbeb'};color:${textMain};border-radius:6px;cursor:pointer;">重置今日执行</button>
        </div>
        <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:12px;">
            <button id="closeBtn" style="padding:8px 14px;border:1px solid ${borderColor};background:${inputBg};color:${textMain};border-radius:6px;cursor:pointer;">关闭</button>
            <button id="saveBtn" style="padding:8px 14px;border:none;background:#2563eb;color:#fff;border-radius:6px;cursor:pointer;">保存全部</button>
        </div>
    </div>
</div>
`;
        const wrap = document.createElement('div');
        wrap.innerHTML = html;
        document.body.appendChild(wrap);
        const panel = wrap.firstElementChild;

        panel.addEventListener('click', (e) => {
            if(e.target === panel) panel.remove();
        });

        panel.querySelectorAll('[data-del]').forEach(btn=>{
            btn.onclick = ()=>{
                const idx = Number(btn.dataset.del);
                taskList.splice(idx,1);
                panel.remove();
                renderPanel();
            }
        });

        panel.querySelectorAll('[data-test]').forEach(btn=>{
            btn.onclick = ()=>{
                const idx = Number(btn.dataset.test);
                runTask(taskList[idx], idx, true);
            }
        });

        // 捕获坐标按钮
        panel.querySelectorAll('[data-capture]').forEach(btn=>{
            btn.onclick = ()=>{
                const idx = Number(btn.dataset.capture);
                captureCoordTaskIndex = idx;
                panel.remove();
                alert("✅ 现在移动鼠标到要点击的位置,点击页面任意位置,自动抓取坐标!");
                const capture = (e)=>{
                    document.removeEventListener('click', capture);
                    if(captureCoordTaskIndex !== null){
                        taskList[captureCoordTaskIndex].x = e.clientX;
                        taskList[captureCoordTaskIndex].y = e.clientY;
                        captureCoordTaskIndex = null;
                    }
                    renderPanel();
                }
                document.addEventListener('click', capture);
            }
        });

        panel.querySelector('#addTaskBtn').onclick = ()=>{
            taskList.push({ enable: false, time: "09:00:00", selector: "", usePos: false, x: 100, y: 100, refreshSec: 10, refreshed: false });
            panel.remove();
            renderPanel();
        }

        panel.querySelector('#resetExecBtn').onclick = ()=>{
            executedToday = [];
            taskList.forEach(t=>t.refreshed = false);
            saveAll();
            alert("✅ 今日执行记录、刷新标记已重置");
        }

        panel.querySelector('#closeBtn').onclick = ()=> panel.remove();

        panel.querySelector('#saveBtn').onclick = ()=>{
            const newList = [];
            const items = panel.querySelectorAll('.task-item');
            let ok = true;
            items.forEach(item=>{
                const timeVal = item.querySelector('.t-time').value.trim();
                if(!isValidTime(timeVal)){
                    ok = false;
                }
                newList.push({
                    enable: item.querySelector('.t-enable').checked,
                    time: timeVal,
                    selector: item.querySelector('.t-sel').value.trim(),
                    usePos: item.querySelector('.t-usePos').checked,
                    x: Number(item.querySelector('.t-x').value),
                    y: Number(item.querySelector('.t-y').value),
                    refreshSec: Number(item.querySelector('.t-refresh').value),
                    refreshed: false
                })
            })
            if(!ok){
                alert("❌ 存在时间格式错误!必须 HH:mm:ss");
                return;
            }
            taskList = newList;
            saveAll();
            alert("✅ 保存成功,刷新页面生效");
            panel.remove();
        }
    }

    function mainLoop() {
        const today = getTodayStr();
        taskList.forEach((task, idx) => {
            if(!task.enable) return;
            const tid = getTaskId(idx);
            if (executedToday.includes(tid)) return;

            const diff = getDiffSec(task.time);
            if (diff > 0) {
                if (diff === task.refreshSec && task.refreshSec > 0 && !task.refreshed) {
                    task.refreshed = true;
                    saveAll();
                    console.log(`⏳ 任务${idx+1} 距离${task.time}还有${diff}秒,准备刷新页面`);
                    location.reload();
                }
                return;
            }
            runTask(task, idx, false);
        })
    }

    GM_registerMenuCommand("⏰ 多任务定时点击 - 设置面板", renderPanel);

    setInterval(mainLoop, 1000);
    console.log(" 多任务定时点击脚本已加载");
})();

posted @ 2026-11-17 14:36  哈哈肚皮  阅读(15)  评论(0)    收藏  举报