// ==UserScript==
// @name         Auto-Rate Posts with Close Handling
// @namespace    http://tampermonkey.net/
// @version      1.21
// @description  Automatically rate posts in a forum thread and handle already rated posts
// @author       Your Name
// @match        https://141love.net/*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    let currentIndex = 0; // To keep track of the current index of the rate button
    const maxRetries = 5; // Max retries for score input fields
    const retryDelay = 500; // Delay between retries in milliseconds

    // Set user-specific ratings and logic based on content
    const ratingLogic = {
        "Juven": { score1: 5, score2: 50, score4: 5 },
        "力王ER": { score1: 5, score2: 50, score4: 5 },

        // Add more usernames and their corresponding ratings as needed
    };

    // Default rating if username is not found in the defined logic
    const defaultRating = { score1: 2, score2: 20, score4: 2 };

    // Function to update input values in the rate form
    function updateInputsAndSubmit(button, retries = 0) {
        const postElement = button.closest('.plhin');
        const score1 = document.querySelector('input#score1.px.z');
        const score2 = document.querySelector('input#score2.px.z');
        const score4 = document.querySelector('input#score4.px.z');

        if (!postElement) {
            console.error('Could not find the post element associated with this button.');
            return;
        }

        const usernameElement = postElement.querySelector('div.authi a.xw1');
        const username = usernameElement ? usernameElement.innerText.trim() : '';
        const messageTextElement = postElement.querySelector('div.t_fsz td.t_f');
        const messageText = messageTextElement ? messageTextElement.innerText : '';

        let rating = ratingLogic[username] || defaultRating;

        // Check if score inputs exist before proceeding
        if (score1 && score2 && score4) {
            score1.value = rating.score1;
            score2.value = rating.score2;
            score4.value = rating.score4;

            console.log(`Setting scores for user: ${username}`);
            console.log('Values set. Attempting to click the correct submit button.');

            const submitButton = document.querySelector('button.pn.pnc:not(.z)');
            if (submitButton) {
                setTimeout(() => {
                    submitButton.click();
                }, 200);
            } else {
                console.log('Submit button not found. Retrying...');
                setTimeout(() => updateInputsAndSubmit(button), 200);
            }
        } else {
            console.error('Score input fields are missing.');
            if (retries < maxRetries) {
                console.log(`Retrying to find score inputs... (${retries + 1}/${maxRetries})`);
                setTimeout(() => updateInputsAndSubmit(button, retries + 1), retryDelay);
            } else {
                console.warn('Max retries exceeded for finding score input fields. Moving to next rate button.');
                currentIndex++;
                setTimeout(clickNextRateButton, 1000);
            }
        }
    }

    function closeFwinWindow() {
        const closeButton = document.querySelector('button#closebtn.pn.pnc');
        if (closeButton) {
            console.log('Already rated window detected. Closing it.');
            closeButton.click();
        }
    }

    function shouldIgnoreMessage(message) {
        const ignoreMessages = ["thanks for sharing", "thx for sharing", "nice", "多謝分享", "多謝師兄分享", "good"];
        const normalizedMessage = message.toLowerCase().replace(/[!.,?;:()]/g, '');
        return ignoreMessages.some(phrase => normalizedMessage.includes(phrase));
    }

    function clickNextRateButton() {
        const rateButtons = Array.from(document.querySelectorAll('a.rateb'));
        if (currentIndex >= rateButtons.length) {
            console.log('All replies have been rated.');
            return;
        }

        const button = rateButtons[currentIndex];
        const postElement = button.closest('.plhin');
        const messageElement = postElement.querySelector('div.t_fsz table tbody tr td.t_f');

        const messageText = messageElement ? messageElement.innerText : "";

        if (shouldIgnoreMessage(messageText)) {
            console.log(`Ignoring post ${currentIndex + 1}: ${messageText}`);
            currentIndex++;
            setTimeout(clickNextRateButton, 1000);
            return;
        }

        if (button) {
            console.log(`Clicking rate button for post index ${currentIndex}`);
            button.click();
            currentIndex++;
        }

        setTimeout(() => {
            const rateWindow = document.getElementById('fwin_rate');
            if (rateWindow) {
                updateInputsAndSubmit(button);
            }

            const alreadyRatedWindow = document.querySelector('table.fwin');
            if (alreadyRatedWindow) {
                closeFwinWindow();
                setTimeout(clickNextRateButton, 500);
            } else {
                setTimeout(clickNextRateButton, 1000);
            }
        }, 1000);
    }

    function automateRating() {
        currentIndex = 0; // Reset the index
        clickNextRateButton(); // Start clicking buttons
    }

    function addAutomationButton(container, buttonText, styles, buttonClass) {
        if (container) {
            const autoButton = document.createElement('button');
            autoButton.innerText = buttonText;
            autoButton.onclick = automateRating;
            Object.assign(autoButton.style, styles);
            autoButton.className = buttonClass;
            container.appendChild(autoButton);
        }
    }

    const style = document.createElement('style');
    style.textContent = `
        .main-button {
            background-color: #FE9510;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 7px 10px;
            font-size: 14.5px;
            cursor: pointer;
            margin: 0px;
            transition: background-color 0.3s, color 0.3s;
        }

        .main-button:hover {
            background-color: #E78F1B;
            color: #FFF;
        }

        .scroll-top-button {
            background-color: #F4F4F4;
            color: #BBBBBB;
            border-top: 1px solid #BBBBBB;
            border-left: none;
            border-bottom: none;
            border-right: none;
            border-radius: 0px;
            padding: 7px 7px;
            font-size: 11px;
            font-weight: bold;
            cursor: pointer;
            margin: 0px;
            writing-mode: horizontal-lr;
            transition: background-color 0.3s, color 0.3s;
        }

        .scroll-top-button:hover {
            background-color: #F4F4F4;
            color: #7DA0CC;
        }
    `;
    document.head.appendChild(style);

    window.addEventListener('load', () => {
        if (window.location.href.includes("thread")) {
            addAutomationButton(document.querySelector('div#pgt.pgs.cl'), '自動評分', {}, 'main-button');
            addAutomationButton(document.querySelector('div#scrolltop'), '自動評分', {}, 'scroll-top-button');
        } else {
            console.log('Not a thread page. Automation buttons will not be added.');
        }
    });
})();

How do I ignore rating for those reply with only a gif file?