Greasy Fork

MoD mode

try to manage the world!

目前为 2024-03-20 提交的版本。查看 最新版本

// ==UserScript==
// @name         MoD mode
// @namespace    http://tampermonkey.net/
// @version      2024-03-20
// @description  try to manage the world!
// @author       You
// @match        https://www.erepublik.com/br
// @icon         https://www.google.com/s2/favicons?sz=64&domain=erepublik.com
// @grant        none
// ==/UserScript==
(function() {
    'use strict';

    // Define the list
    const _token = csrfToken;
    const dateTime = SERVER_DATA.serverTime.dateTime;
    let message = `*Philippines TW* \n`;
    var list = [{
        war_id: 205525,
        id: 639847,
        country_id: 49
    }, {
        war_id: 205903,
        id: 639992,
        country_id: 81
    }, {
        war_id: 206105,
        id: 640137,
        country_id: 10
    }, {
        war_id: 209808,
        id: 639948,
        country_id: 59
    }, {
        war_id: 211305,
        id: 639829,
        country_id: 24
    }, {
        war_id: 211391,
        id: 639907,
        country_id: 31
    }, {
        war_id: 212392,
        id: 640151,
        country_id: 15
    }, {
        war_id: 213683,
        id: 639924,
        country_id: 168
    }, {
        war_id: 213982,
        id: 639720,
        country_id: 54
    }, {
        war_id: 213988,
        id: 639668,
        country_id: 164
    }, {
        war_id: 214058,
        id: 640024,
        country_id: 82
    }, {
        war_id: 214111,
        id: 640346,
        country_id: 77
    }, {
        war_id: 214188,
        id: 641830,
        country_id: 169
    }];

    mainFunction();

    async function mainFunction() {
        const fetchTime = getCurrentUnixTimestamp();
        const fetchlist = await fetchData(`https://www.erepublik.com/en/military/campaignsJson/list?${fetchTime}`);

        for (let item of list) {
            let country = fetchlist.countries[item.country_id].name;

            // Call the function to check if war ID exists
            let result = await isWarIdExist(fetchlist, item.war_id); // Ensure to await the result
            let exists = result.exists;
            let battleData = result.battle;
            console.log(result);
            if (exists) {
                const region = battleData.region.name;
                const defC = fetchlist.countries[battleData.def.id].name;
                const defP = battleData.def.points;
                const invC = fetchlist.countries[battleData.inv.id].name;
                const invP = battleData.inv.points;
                console.log(region);
                message += `\n*${region}*\n🛡: ${defC} : ${defP} Points \n🗡: ${invC} : ${invP} Points\n`;
            } else {
                const battleId = item.id;
                const payload = payloadList(battleId, _token);
                const url = `https://www.erepublik.com/en/military/battle-console`
                const list = await PostRequest(payload, url);
                console.log(list.list[0].result);
                const result = list.list[0].result;
                const outcome = result.outcome;
                const winner = result.winner;

                if (outcome === "defense" && winner === "Philippines") {
                    const endTime = result.end;
                    var times = compareTime(dateTime, endTime);
                    console.log("Difference between dateTime and resultEnd:", times);
                    message += `\nAttack *${country}* - auto in ${times}\n [${item.war_id}](https://www.erepublik.com/en/wars/show/${item.war_id})\n`;

                } else {
                    message += `\nWaiting attack from *${country}*\n`;

                }
                await delay(3000);
                console.log("War ID", item.war_id, "does not exist in battles.");
            }

            console.log("------------------------");
        }
        sendMessage(message);
    }


    // Function to check if a war_id exists in fetchlist.battles
    function isWarIdExist(fetchlist, warId) {
        for (let battleId in fetchlist.battles) {
            if (fetchlist.battles.hasOwnProperty(battleId)) {
                if (fetchlist.battles[battleId].war_id === warId) {
                    return {
                        exists: true,
                        battle: fetchlist.battles[battleId]
                    };
                }
            }
        }
        return {
            exists: false,
            battle: null
        };
    }

    // Function to get current UNIX timestamp
    function getCurrentUnixTimestamp() {
        const currentTime = new Date();
        const unixTimestamp = Math.floor(currentTime.getTime() / 1000); // Convert milliseconds to seconds
        return unixTimestamp;
    }

    // Function to introduce a delay
    function delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    // Function to fetch data from a URL
    async function fetchData(url) {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            const data = await response.json();
            return data;
        } catch (error) {
            throw new Error(`Failed to fetch data from ${url}: ${error.message}`);
        }
    }


    async function PostRequest(payload, url) {
        try {
            const response = await fetch(url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: Object.keys(payload)
                    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(payload[key])}`)
                    .join('&')
            });

            const responseData = await response.json();
            return responseData;
        } catch (error) {
            console.error("Error:", error);
            return null;
        }
    }

    // Function to construct the payload from variables
    function payloadList(battleId, _token) {
        const action = "warList";
        const Page = 1;


        return {
            battleId,
            action,
            Page,
            _token
        };
    }


    function compareTime(dateTime, resultEnd) {
        // Convert dateTime and resultEnd to Unix timestamps
        var dateTimeUnix = (new Date(dateTime)).getTime() / 1000;
        var resultEndUnix = (new Date(resultEnd)).getTime() / 1000;

        // If resultEnd is earlier than dateTime, add 24 hours to resultEnd
        if (resultEndUnix < dateTimeUnix) {
            resultEndUnix += 24 * 3600; // 24 hours in seconds
        }

        // Calculate the difference in seconds
        var differenceInSeconds = Math.abs(dateTimeUnix - resultEndUnix);

        // Convert difference to HH:MM:SS format
        var hours = Math.floor(differenceInSeconds / 3600);
        var minutes = Math.floor((differenceInSeconds % 3600) / 60);
        var seconds = Math.floor(differenceInSeconds % 60);

        // Format the difference as HH:MM:SS
        var formattedDifference = hours.toString().padStart(2, '0') + ":" +
            minutes.toString().padStart(2, '0') + ":" +
            seconds.toString().padStart(2, '0');

        return formattedDifference;
    }

    function sendMessage(message) {
        var botToken = '6423448975:AAGmYbAXaC0rTuIDH-2SoNXhjPLdjayX35c';
        var chatId = '-1002078934269';

        var apiUrl = 'https://api.telegram.org/bot' + botToken + '/sendMessage?chat_id=' + chatId + '&text=' + encodeURIComponent(message) + '&parse_mode=markdown&disable_web_page_preview=true';

        // Make the HTTP request
        fetch(apiUrl)
            .then(response => response.json())
            .then(data => console.log(data))
            .catch(error => console.error('Error:', error));
    }




})();