New but 0Ld

Too lazy to do something, it's old but new

// ==UserScript==
// @name         New but 0Ld
// @namespace    erepFarm
// @version      1.666.7
// @description  Too lazy to do something, it's old but new
// @author       You
// @match        https://www.erepublik.com/en
// @grant        none
// @run-at		document-end
// ==/UserScript==
(function() {

    // Main function to perform the main task
    async function mainFunction() {
        const energymin = 30;
        const weapQu = 10;
        const energy = erepublik.citizen.energy;
        const countryLocationId = erepublik.citizen.countryLocationId;
        const division = erepublik.citizen.division;
        const _token = csrfToken;
        const countryList = [1, 9, 14, 15, 23, 24, 29, 31, 35, 38, 39, 40, 42, 45, 47, 49, 51, 52, 53, 56, 59, 65, 66, 67, 68, 70, 71, 72, 78, 79, 81, 166];
        let idbattle = [];

        const zone = await fetchData("https://www.erepublik.com/en/military/campaignsJson/citizen");
        await delay(2000);
        const list = await fetchData("https://www.erepublik.com/en/military/campaignsJson/list");

        if (zone && list) {
            let allBattle = list.battles;
            let allZone = zone.battles;
            const countries = list.countries;

            // Create an empty array to store the country names
            const countryNames = [];

            // Iterate through the countryList and retrieve names
            for (const countryId of countryList) {
                if (countries.hasOwnProperty(countryId)) {
                    countryNames.push(countries[countryId].name);
                }
            }

            createDivElement('emptyBattle', 'sidebar', 'Battle List: ');
            createDivElement('list', 'sidebar', '');


            for (let battleId in allBattle) {
                if (allBattle.hasOwnProperty(battleId)) {
                    try {
                        let battle = allBattle[battleId];
                        let ground = allZone[battleId].groundZoneId;
                        let dw = battle.war_type;
                        let countryLocationIds = [countryLocationId];
                        let side = countryLocationId;


                        if (dw == "direct") {
                            const inv = battle.inv.id;
                            const def = battle.def.id;
                            const inva = battle.inv.allies;
                            const defa = battle.def.allies;

                            let check = false;

                            if (countryList.includes(inv) && countryList.includes(def)) {
                                if (inv === countryLocationId || def === countryLocationId) {
                                    check = true;
                                }

                                if (inva.includes(countryLocationId)) {
                                    check = true;
                                    countryLocationIds.push(inv);
                                    side = inv;
                                }
                                if (defa.includes(countryLocationId)) {
                                    check = true;
                                    countryLocationIds.push(def);
                                    side = def;
                                }
                            }

                            if (check == true) {
                                const region = battle.region.name;
                                const round = battle.zone_id;
                                const loadstat = payloadStat(battleId, round, round, division, ground, _token);
                                const stat = await battleStat(loadstat);
                                const empty = checkFighterDataEmpty(stat, countryLocationIds);

                                // Check if stat.rounds[ground] is defined before accessing its properties
                                if (stat.rounds[ground]) {
                                    const end = stat.rounds[ground].finished;
                                    const start = stat.rounds[ground].started;

                                    console.log("Battle ID", battle.id);
                                    console.log("empty?", empty);


                                    if (start == 1 && end == 0 && empty == true) {
                                        // Check inventory
                                        const inventLoad = inventoryPayload(battleId, side, ground, _token);
                                        const inventory = await inventoryCheck(inventLoad);
                                        const listweapon = inventory.weapons;
                                        const vehicles = inventory.vehicles;

                                        // Skin
                                        const skinRecommended = vehicles.find(skin => skin.isRecommended === true);
                                        let skinId;

                                        if (skinRecommended) {
                                            skinId = skinRecommended.id;
                                        }

                                        // Find the object with quality 10 in the weapons response array
                                        const objectWithQuality = listweapon.find(item => item.quality === weapQu);
                                        let weaponAmount;
                                        let totalEnergy;
                                        if (objectWithQuality) {
                                            weaponAmount = objectWithQuality.amount;
                                        }
                                        if (weaponAmount >= 2 && energy > energymin) {
                                            totalEnergy = 11;
                                            const depLoad = deployLoad(battleId, ground, side, weapQu, totalEnergy, skinId, _token);
                                            await deployDamage(depLoad);
                                            await delay(2000);

                                            const linkText = `${region} - EMPTY`;
                                            const linkUrl = `https://www.erepublik.com/en/military/battlefield/${battleId}/${ground}`;
                                            displayLinkInHtml('list', linkText, linkUrl);
                                            await delay(3000);
                                        }
                                    } else {
                                        const linkText = `${region} - SKIP`;
                                        const linkUrl = `https://www.erepublik.com/en/military/battlefield/${battleId}/${ground}`;
                                        displayLinkInHtml('list', linkText, linkUrl);
                                    }
                                    await delay(2000);

                                    console.log("-------------------------");
                                } else {
                                    console.error("stat.rounds[ground] is undefined for battle ID " + battleId);
                                }
                            }
                        } // end if direct
                    } catch (error) {
                        // Handle the error for this iteration
                        console.error("An error occurred in iteration for battle ID " + battleId + ": " + error);
                    }
                }
            } //end for looping
            createDivElement('end', 'sidebar', '---END---');

            createDivElement('listCountry', 'sidebar', 'List Country:');
            countryNames.forEach(function(countryName) {
                const elementId = "yourElementId"; // Replace with the actual element ID
                createDivElement('countryName', 'sidebar', countryName);
            });
        }


    }

    //list of function

    // Function to send GET request and fetch JSON data
    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}`);
        }
    }

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

    // Function to construct the payload from variables
    function payloadStat(battleId, zoneId, round, division, battleZoneId, _token) {
        const action = "battleStatistics";
        const type = "damage";
        const leftPage = 1;
        const rightPage = 1;

        return {
            battleId,
            zoneId,
            action,
            round,
            division,
            battleZoneId,
            type,
            leftPage,
            rightPage,
            _token
        };
    }

    // Function to send the payload using POST request
    async function battleStat(payload) {
        const url = "https://www.erepublik.com/en/military/battle-console";

        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 check if country.fighterData is empty and push to new array if empty
    function checkFighterDataEmpty(responseData, countryLocationIds) {
        for (const countryLocationId of countryLocationIds) {
            if (responseData && responseData[countryLocationId] && responseData[countryLocationId]["fighterData"]) {
                const fighterData = responseData[countryLocationId]["fighterData"];
                if (Object.keys(fighterData).length > 0) {
                    return false;
                }
            }
        }
        return true; // Return false if none of the countryIds have non-empty fighterData
    }

    //payload for inventory
    function inventoryPayload(battleId, sideCountryId, battleZoneId, _token) {
        return {
            battleId,
            sideCountryId,
            battleZoneId,
            _token
        };
    }

    //function to check inventory
    async function inventoryCheck(payload) {
        const url = "https://www.erepublik.com/en/military/fightDeploy-getInventory";

        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 create a new div element inside a parent element
    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 deploy
    function deployLoad(battleId, battleZoneId, sideCountryId, weaponQuality, totalEnergy, skinId, _token) {
        return {
            battleId,
            battleZoneId,
            sideCountryId,
            weaponQuality,
            totalEnergy,
            skinId,
            _token
        };
    }

    // Function to send a POST request for fight deploy
    async function deployDamage(payload) {
        const url = 'https://www.erepublik.com/en/military/fightDeploy-startDeploy';

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




    //end of line
    // Call the main function when the page loads
    window.addEventListener('load', mainFunction);
})();