MoD mode

try to manage the world!

目前為 2024-04-25 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         MoD mode
// @namespace    http://tampermonkey.net/
// @version      2024-04-25
// @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,
        region: 465
    }, {
        war_id: 205903,
        id: 639992,
        country_id: 81,
        region: 464
    }, {
        war_id: 206105,
        id: 640137,
        country_id: 10,
        region: 270
    }, {
        war_id: 209808,
        id: 639948,
        country_id: 59,
        region: 510
    }, {
        war_id: 211305,
        id: 639829,
        country_id: 24,
        region: 50
    }, {
        war_id: 211391,
        id: 639907,
        country_id: 31,
        region: 704
    }, {
        war_id: 212392,
        id: 640151,
        country_id: 15,
        region: 171
    }, {
        war_id: 213683,
        id: 639924,
        country_id: 168,
        region: 750
    }, {
        war_id: 213982,
        id: 639720,
        country_id: 54,
        region: 271
    }, {
        war_id: 213988,
        id: 639668,
        country_id: 164,
        region: 728
    }, {
        war_id: 214058,
        id: 640024,
        country_id: 82,
        region: 724
    }, {
        war_id: 214111,
        id: 640346,
        country_id: 77,
        region: 641
    }, {
        war_id: 214188,
        id: 641830,
        country_id: 169,
        region: 178
    }, {
        war_id: 214656,
        id: 652852,
        country_id: 165,
        region: 749
    }];

    mainFunction();

    async function mainFunction() {
        createDivElement('scan', 'sidebar', 'SCANNING ALL BATTLE');
        createDivElement('list', 'sidebar', '');
        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 ready = await checkRegionExistence(fetchlist, item.region);
                    let rta =  `*not ready*`;
                    if(ready){
                        rta = `*ready*`;
                    }
                    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}) ${rta}\n`;
                    const linkText = `Attack ${country} - auto in ${times}`;
                    const linkUrl = `https://www.erepublik.com/en/wars/show/${item.war_id}`;
                    displayLinkInHtml('list', linkText, linkUrl);

                } 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);
        createDivElement('send', 'sidebar', 'DATA SENT TO CHANNEL');
    }


    // 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 checkRegionExistence(object, regionId) {
        // Iterate over battles object
        for (const battleId in object.battles) {
            const battle = object.battles[battleId];
            // Check if region id matches
            if (battle.region && battle.region.id === regionId) {
                // If region id exists, return false
                return false;
            }
        }
        // If region id doesn't exist, return true
        return true;
    }

    // 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 createDivElement(divId, parentId, textContent) {
        const parentElement = document.querySelector(`.${parentId}`);
        if (parentElement) {
            const newDiv = document.createElement('div');
            newDiv.id = divId;
            newDiv.textContent = textContent;
            parentElement.appendChild(newDiv);
        } else {
            console.error(`Parent element with class '${parentId}' not found.`);
        }
    }

    // Function to display any value in HTML
    function displayValueInHtml(elementId, value) {
        const element = document.getElementById(elementId);
        if (element) {
            element.textContent = `${element.textContent} ${value}`;
        } else {
            console.error(`Element with ID '${elementId}' not found.`);
        }
    }

    function displayLinkInHtml(containerId, linkText, linkUrl) {
        const containerElement = document.getElementById(containerId);
        if (containerElement) {
            const linkElement = document.createElement('a');
            linkElement.href = linkUrl;
            linkElement.target = '_blank';
            linkElement.textContent = linkText;
            containerElement.appendChild(linkElement);
            containerElement.appendChild(document.createElement('br'));
        } else {
            console.error(`Container element with ID '${containerId}' not found.`);
        }
    }

    // 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));
    }




})();