Greasy Fork

Monitor

try to monitor the world!

目前为 2024-06-23 提交的版本。查看 最新版本

// ==UserScript==
// @name         Monitor
// @namespace    IndoMod
// @version      2024-06-23
// @description  try to monitor the world!
// @author       You
// @match        https://www.erepublik.com/id
// @icon         https://www.google.com/s2/favicons?sz=64&domain=erepublik.com
// @grant        none
// ==/UserScript==
(function() {
    'use strict';

    const war = 215884;
    const friend = 49;
    const enemy = 44;
    const _token = csrfToken;

    const countriesData = [
    { "id": 1, "name": "Romania", "flag": "🇷🇴" },
    { "id": 9, "name": "Brazil", "flag": "🇧🇷" },
    { "id": 10, "name": "Italy", "flag": "🇮🇹" },
    { "id": 11, "name": "France", "flag": "🇫🇷" },
    { "id": 12, "name": "Germany", "flag": "🇩🇪" },
    { "id": 13, "name": "Hungary", "flag": "🇭🇺" },
    { "id": 14, "name": "China", "flag": "🇨🇳" },
    { "id": 15, "name": "Spain", "flag": "🇪🇸" },
    { "id": 23, "name": "Canada", "flag": "🇨🇦" },
    { "id": 24, "name": "USA", "flag": "🇺🇸" },
    { "id": 26, "name": "Mexico", "flag": "🇲🇽" },
    { "id": 27, "name": "Argentina", "flag": "🇦🇷" },
    { "id": 28, "name": "Venezuela", "flag": "🇻🇪" },
    { "id": 29, "name": "United Kingdom", "flag": "🇬🇧" },
    { "id": 30, "name": "Switzerland", "flag": "🇨🇭" },
    { "id": 31, "name": "Netherlands", "flag": "🇳🇱" },
    { "id": 32, "name": "Belgium", "flag": "🇧🇪" },
    { "id": 33, "name": "Austria", "flag": "🇦🇹" },
    { "id": 34, "name": "Czech Republic", "flag": "🇨🇿" },
    { "id": 35, "name": "Poland", "flag": "🇵🇱" },
    { "id": 36, "name": "Slovakia", "flag": "🇸🇰" },
    { "id": 37, "name": "Norway", "flag": "🇳🇴" },
    { "id": 38, "name": "Sweden", "flag": "🇸🇪" },
    { "id": 39, "name": "Finland", "flag": "🇫🇮" },
    { "id": 40, "name": "Ukraine", "flag": "🇺🇦" },
    { "id": 41, "name": "Russia", "flag": "🇷🇺" },
    { "id": 42, "name": "Bulgaria", "flag": "🇧🇬" },
    { "id": 43, "name": "Turkey", "flag": "🇹🇷" },
    { "id": 44, "name": "Greece", "flag": "🇬🇷" },
    { "id": 45, "name": "Japan", "flag": "🇯🇵" },
    { "id": 47, "name": "South Korea", "flag": "🇰🇷" },
    { "id": 48, "name": "India", "flag": "🇮🇳" },
    { "id": 49, "name": "Indonesia", "flag": "🇮🇩" },
    { "id": 50, "name": "Australia", "flag": "🇦🇺" },
    { "id": 51, "name": "South Africa", "flag": "🇿🇦" },
    { "id": 52, "name": "Republic of Moldova", "flag": "🇲🇩" },
    { "id": 53, "name": "Portugal", "flag": "🇵🇹" },
    { "id": 54, "name": "Ireland", "flag": "🇮🇪" },
    { "id": 55, "name": "Denmark", "flag": "🇩🇰" },
    { "id": 56, "name": "Iran", "flag": "🇮🇷" },
    { "id": 57, "name": "Pakistan", "flag": "🇵🇰" },
    { "id": 58, "name": "Israel", "flag": "🇮🇱" },
    { "id": 59, "name": "Thailand", "flag": "🇹🇭" },
    { "id": 61, "name": "Slovenia", "flag": "🇸🇮" },
    { "id": 63, "name": "Croatia", "flag": "🇭🇷" },
    { "id": 64, "name": "Chile", "flag": "🇨🇱" },
    { "id": 65, "name": "Serbia", "flag": "🇷🇸" },
    { "id": 66, "name": "Malaysia", "flag": "🇲🇾" },
    { "id": 67, "name": "Philippines", "flag": "🇵🇭" },
    { "id": 68, "name": "Singapore", "flag": "🇸🇬" },
    { "id": 69, "name": "Bosnia and Herzegovina", "flag": "🇧🇦" },
    { "id": 70, "name": "Estonia", "flag": "🇪🇪" },
    { "id": 71, "name": "Latvia", "flag": "🇱🇻" },
    { "id": 72, "name": "Lithuania", "flag": "🇱🇹" },
    { "id": 73, "name": "North Korea", "flag": "🇰🇵" },
    { "id": 74, "name": "Uruguay", "flag": "🇺🇾" },
    { "id": 75, "name": "Paraguay", "flag": "🇵🇾" },
    { "id": 76, "name": "Bolivia", "flag": "🇧🇴" },
    { "id": 77, "name": "Peru", "flag": "🇵🇪" },
    { "id": 78, "name": "Colombia", "flag": "🇨🇴" },
    { "id": 79, "name": "North Macedonia", "flag": "🇲🇰" },
    { "id": 80, "name": "Montenegro", "flag": "🇲🇪" },
    { "id": 81, "name": "Republic of China (Taiwan)", "flag": "🇹🇼" },
    { "id": 82, "name": "Cyprus", "flag": "🇨🇾" },
    { "id": 83, "name": "Belarus", "flag": "🇧🇾" },
    { "id": 84, "name": "New Zealand", "flag": "🇳🇿" },
    { "id": 164, "name": "Saudi Arabia", "flag": "🇸🇦" },
    { "id": 165, "name": "Egypt", "flag": "🇪🇬" },
    { "id": 166, "name": "United Arab Emirates", "flag": "🇦🇪" },
    { "id": 167, "name": "Albania", "flag": "🇦🇱" },
    { "id": 168, "name": "Georgia", "flag": "🇬🇪" },
    { "id": 169, "name": "Armenia", "flag": "🇦🇲" },
    { "id": 170, "name": "Nigeria", "flag": "🇳🇬" },
    { "id": 171, "name": "Cuba", "flag": "🇨🇺" }
];

    mainFunction();

    async function mainFunction() {
        const capthca = checkSessionValidationExists();
        if (!capthca) {
            const friendName = countryName(friend);
            const enemyName = countryName(enemy);
            const fetchTime = getCurrentUnixTimestamp();
            const fetchlist = await fetchData(`https://www.erepublik.com/en/military/campaignsJson/list?${fetchTime}`);
            const battles = fetchlist.battles;
            const battleId = findBattleByWarId(battles, war);

            if (battleId) {
                const urlB = `https://www.erepublik.com/id/military/battlefield/${battleId}`;
                await delay(500);
                const monitor = battles[battleId];
                console.log(monitor);

                const start = monitor.start;
                const zoneId = monitor.zone_id;
                const region = monitor.region.name;
                const critical = start + 4790;

                let message = `*Battle ${region} R${zoneId}*\n${urlB}\n\nFIGHT FOR ${friendName}`;
                const now = getCurrentUnixTimestamp();
                const time = Math.abs(start - now);
                const timer = sToMMSS(time);

                if (now < start) {
                    //inform channel that battle will start in
                    message += `\nWill start in ${timer}`;
                    sendMessage(message);
                    await delay(time*900);
                    redirectToErepublik()
                } else {
                    const div = monitor.div;
                    const divisions = Object.values(div);
                    message += `\nBattle Time: ${timer}\n`;

                    for (const division of divisions) {
                        const d = division.div;
                        const battleZoneId = division.id;
                        const wallDom = division.wall.dom;
                        const wallFor = division.wall.for;

                        const checkLoad = chart(battleId, zoneId, d, battleZoneId, _token);
                        const battleStatURL = `https://www.erepublik.com/id/military/battle-console`;
                        const charts = await PostRequest(checkLoad, battleStatURL);
                        await delay(1000);
                        const chartData = findLatestMinuteObject(charts);
                        const defender = chartData.defender_overall_damage;
                        const invader = chartData.invader_overall_damage;
                        const difference = formatNumberWithCommas(Math.abs(defender - invader));
                        const overall = defender + invader;
                        const dpp = formatNumberWithCommas(Math.floor(overall/100));

                        if(wallFor != friend){
                            if(wallDom == 50 || wallDom == 100){
                                message += `\nDivision ${d} *NEED HITTER*`;
                            } else {
                                message +=`\nDivision ${d} *NEED ${difference} DAMAGE*\nDOM: ${wallDom}% (LOSE)\nDamage per 1% : ${dpp}\n`;
                            }
                        } else {
                            message += `\nDivision ${d} : *DOM: ${wallDom}% (WIN)*\nDamage per 1% : ${dpp}\n`;
                        }
                    }
                    if (now < critical) {
                        sendMessage(message);
                        await delay(600000);
                        redirectToErepublik()
                    } else {
                        message += `\nCRITICAL!!`;
                        sendMessage(message);
                        await delay(60000);
                        redirectToErepublik()
                    }
                }
            }

        }
    }

    function checkSessionValidationExists() {
        if (typeof SERVER_DATA !== 'undefined' && SERVER_DATA.sessionValidation !== undefined) {
            return true;
        } else {
            return false;
        }
    }

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

    function sToMMSS(seconds) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;

        const formattedMinutes = String(minutes).padStart(2, '0');
        const formattedSeconds = String(remainingSeconds).padStart(2, '0');

        return `${formattedMinutes}:${formattedSeconds}`;
    }


    function delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    function redirectToErepublik() {
        window.location.href = "https://www.erepublik.com/id";
    }

    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) {
            redirectToErepublik();
            throw new Error(`Failed to fetch data from ${url}: ${error.message}`);

        }
    }

    // Function to find the battle ID by war_id
    function findBattleByWarId(battles, warId) {
        for (const key in battles) {
            if (battles[key].war_id === warId) {
                return battles[key].id;
            }
        }
        return null;
    }

    function countryName(inputId) {
    const country = countriesData.find(country => country.id === inputId);
    return country ? `${country.flag} ${country.name}` : "Country not found";
}

    function formatNumberWithCommas(number) {
    // Convert number to string
    let numStr = number.toString();

    // Split the integer part from the decimal part (if exists)
    let parts = numStr.split(".");
    let integerPart = parts[0];
    let decimalPart = parts.length > 1 ? "." + parts[1] : "";

    // Add commas to the integer part
    let formattedIntegerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",");

    // Concatenate integer and decimal parts
    return formattedIntegerPart + decimalPart;
}

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

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

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


    //payload

    function chart(battleId, zoneId, division, battleZoneId, _token) {
        const page = 1;
        const action = "charts";
        return {
            battleId,
            page,
            zoneId,
            division,
            action,
            battleZoneId,
            _token
        };
    }

    function findLatestMinuteObject(data) {
    if (data.length === 0) return null;

    let latestObject = data[0];

    for (let i = 1; i < data.length; i++) {
        if (data[i].minute > latestObject.minute) {
            latestObject = data[i];
        }
    }

    return latestObject;
}


})();