New Something c00L

Too lazy to do something

Versione datata 11/09/2023. Vedi la nuova versione l'ultima versione.

// ==UserScript==
// @name         New Something c00L
// @namespace    erepFarm
// @version      0.1.666
// @description  Too lazy to do something
// @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() {
    let energy = erepublik.citizen.energy;

    if(energy > 120){
        try {
            let aircraft = true;
            let _token = csrfToken;
            let countryLocationId = erepublik.citizen.countryLocationId;
            let division;
    
            if(aircraft == true){division = 11;}
            else {division = erepublik.citizen.division;}
    
            const zone = await fetchData("https://www.erepublik.com/en/military/campaignsJson/citizen");
    
            // Add a delay of 0.8 seconds
            await delay(800);
    
            const list = await fetchData("https://www.erepublik.com/en/military/campaignsJson/list");
    
            //separate battle target to array
            for (const battleId in list.battles) {
                if (list.battles.hasOwnProperty(battleId)) {
                    const battle = list.battles[battleId];
                    const zoneId = zone.battles[battleId];
                    const battleType = battle.war_type;
                    const round = battle.zone_id;
                    const rnow = round;
                    let battleZoneId;
                    let end;

                    if(zoneId && aircraft == true){battleZoneId = zoneId.aircraftZoneId;}
                    else {battleZoneId = battleZoneId = zoneId.groundZoneId;}

                    if(battleType == "direct"){
                        const inv = battle.inv.id;
                        const def = battle.def.id;
                        
                        //for lose TW battle
                        if (inv == countryLocationId){ 
                            const batstaturl = `https://www.erepublik.com/en/military/battle-stats/${battleId}/${division}/${battleZoneId}`;
                            const getbatstat = await fetchData(batstaturl);
                            end = getbatstat.zone_finished;
                            await delay(2000);

                            if(end == false){
                                const payloadBStat = payloadStat(battleId, round, rnow, division, battleZoneId, _token);
                                const stat = await battleStat(payloadBStat);
                                const empty = checkFighterDataEmpty(stat, countryLocationId);
                                console.log("end?",end);


                            console.log(stat);
                            console.log("empty?",empty);

                                if (empty == true){
                                    //check damage per hit
                                    const inventoryLoad = inventoryPayload(battleId, countryLocationId, battleZoneId, _token);
                                    const inventory = await inventoryCheck(inventoryLoad);
                                    console.log(inventory);


                                    //check opposite total damage
                                    const opposite = checkFighterDataEmpty(stat, def);
                                    console.log ("empty?",opposite);
                                    if (opposite == false){
                                        const totDamage = calculateTotalValue(stat, def)
                                        console.log("Total Value: ",totDamage);
                                    }
                                }
                            
                                await delay(2500);
                            }                                                       
                        }
                    }
                }
            }
        } catch (error) {
            console.error("Error fetching data:", error);
        }
    }
}

//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, countryLocationId) {
        if (responseData && responseData[countryLocationId] && responseData[countryLocationId]["fighterData"]) {
            const fighterData = responseData[countryLocationId]["fighterData"];
            const isFighterDataEmpty = Object.keys(fighterData).length === 0;
            return isFighterDataEmpty;
        } else {
            console.log(`Could not find ${countryLocationId}.fighterData in the response.`);
        }
    }

    // Function to calculate the total value
    function calculateTotalValue(data, countryId) {
        let totalValue = 0;
        const fighterData = data[countryId]?.fighterData || {};
      
        for (const key in fighterData) {
          if (fighterData.hasOwnProperty(key)) {
            const value = fighterData[key].value;
            if (typeof value === 'string') {
              const parsedValue = parseInt(value.replace(/,/g, ''), 10);
              if (!isNaN(parsedValue)) {
                totalValue += parsedValue;
              }
            }
          }
        }
      
        return totalValue;
      }

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


    
            








    


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