Checking S0mething 2

Find S0mething in s0mewhere

// ==UserScript==
// @name         Checking S0mething 2
// @version      1.666.0
// @description  Find S0mething in s0mewhere
// @author       S0me1
// @match        https://www.erepublik.com/en
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_addStyle
// @namespace https://greasyfork.org/users/1144622
// ==/UserScript==

(function () {
    // Function to construct the payload from variables
function constructPayload(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 sendPayload(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 construct the payload for inventory
function constructPayloadForInventory(battleId, sideCountryId, battleZoneId, _token) {
    return {
        battleId,
        sideCountryId,
        battleZoneId,
        _token
    };
}

// Function to send the payload using POST request (modified for inventory)
async function sendPayloadForInventory(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 construct the payload for fight deploy
function constructPayloadForFightDeploy(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 sendPostRequestForFightDeploy(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;
    }
}

// Function to check if country.fighterData is empty and push to new array if empty
function checkFighterDataEmpty(responseData, battleId, countryLocationId, emptyBattleIds) {
    if (responseData && responseData[countryLocationId] && responseData[countryLocationId]["fighterData"]) {
        const fighterData = responseData[countryLocationId]["fighterData"];
        const isFighterDataEmpty = Object.keys(fighterData).length === 0;
        console.log(`Is ${countryLocationId}.fighterData empty?`, isFighterDataEmpty);

        if (isFighterDataEmpty) {
            emptyBattleIds.push(battleId);
        }
    } else {
        console.log(`Could not find ${countryLocationId}.fighterData in the response.`);
    }
}

// Function to process battles and update data arrays
async function processBattles(countryList, division, countryLocationId, _token) {
    // Fetch data from the first URL
    const response1 = await fetch("https://www.erepublik.com/en/military/campaignsJson/list");
    const data1 = await response1.json();

    let dataBattle = {}; // Store battle data by ID
    let idbattle = [];   // Store battle IDs

    // Get battles object from the first JSON file
    var battles1 = data1.battles;

    for (var battleId in battles1) {
        if (battles1.hasOwnProperty(battleId)) {
            var battle = battles1[battleId];
            var dw = battle.war_type;

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

                if (countryList.includes(inv) && countryList.includes(def)) {
                    if (inv === countryLocationId || def === countryLocationId) {
                        dataBattle[battle.id] = battle;
                        idbattle.push(battle.id);
                    }

                    if (inva.includes(countryLocationId) || defa.includes(countryLocationId)){
                        dataBattle[battle.id] = battle;
                        idbattle.push(battle.id);
                    }
                }
            }
        }
    }

	await delay(2000); // 1000 milliseconds = 1 second
    // Fetch data from the second URL
    const response2 = await fetch("https://www.erepublik.com/en/military/campaignsJson/citizen");
    const data2 = await response2.json();

    // Get battles object from the second JSON file
    var battles2 = data2.battles;

    // Prepare dataDivision object
    let dataDivision = {};

    for (let i = 0; i < idbattle.length; i++) {
        let battleId = idbattle[i];

        // Check if the battleId exists in the battles object from the second JSON file
        if (battles2.hasOwnProperty(battleId)) {
            // Store the relevant battle data in the dataDivision object using battle ID as the index
            dataDivision[battleId] = battles2[battleId].selectedBattleZoneId;
        }
    }

    return { dataBattle, idbattle, dataDivision };
}

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

// Main function
async function main() {
    let division = erepublik.citizen.division; // Using citizen's division
    let _token = csrfToken; // Replace with actual _token

    // Assuming erepublik is defined and citizen.countryLocationId is accessible
    let countryLocationId = erepublik.citizen.countryLocationId;

    // Declare the countryList array for later use
    var countryList = [9, 42, 23, 14, 70, 39, 48, 49, 54, 56, 71, 72, 66, 57, 67, 35, 53, 81, 1, 68, 30, 40, 24];

    // Process battles and update data arrays
    const { dataBattle, idbattle, dataDivision } = await processBattles(countryList, division, countryLocationId, _token);

    console.log("dataBattle:", dataBattle);     // Print dataBattle to console
    console.log("idbattle:", idbattle);         // Print idbattle to console
    console.log("dataDivision:", dataDivision); // Print dataDivision to console

    // Create an array to store empty battle IDs
    let emptyBattleIds = [];

    // Iterate through each battle ID and perform a task
    for (let i = 0; i < idbattle.length; i++) {
        let currentBattleId = idbattle[i];
        let selectedBattleZoneId = dataDivision[currentBattleId];
        let cb = dataBattle[currentBattleId];
        let zoneId = cb.zone_id;  // Using zone_id from dataBattle
        let round = zoneId;     // Using round from dataBattle

        // Perform your task here for each battle ID
        console.log(`Task for battle ID ${currentBattleId}: selectedBattleZoneId = ${selectedBattleZoneId}`);

        // Example: You can use this data to construct a payload and send it using sendPayload function
        const payload = constructPayload(currentBattleId, zoneId, round, division, selectedBattleZoneId, _token);
        const responseData = await sendPayload(payload);

        // Call the function and pass currentBattleId, countryLocationId, and emptyBattleIds
        checkFighterDataEmpty(responseData, currentBattleId, countryLocationId, emptyBattleIds);
	await delay(1000); // 1000 milliseconds = 1 second
    }

    // Print the array of empty battle IDs
    console.log("Empty Battle IDs:", emptyBattleIds);

    // Continue with other functions and logic here

    // Iterate through each emptyBattleIds and perform a task
    for (let j = 0; j < emptyBattleIds.length; j++) {
	let target = emptyBattleIds[j];
	let zonetarget = dataDivision[target];

	const payload2 = constructPayloadForInventory(target, countryLocationId, zonetarget, _token);
	const inventory = await sendPayloadForInventory(payload2);
	const listweapon = inventory.weapons;
	const energya = inventory.poolEnergy;
	const vehicles = inventory.vehicles;
	const weaponQuality = 10; //change with weapon that you want to use
	const energyuse = 15; //change with energy to deploy

	// Find the object with quality 10 in the weapons response array
	const objectWithQuality = listweapon.find(item => item.quality === weaponQuality);

	// Get the value of the 'amount' property if the object is found
    	let weaponAmount = null;
    	if (objectWithQuality) {
        	weaponAmount = objectWithQuality.amount;
    	}

	// Find the object with vehicle isRecommended:true
	const skinRecommended = vehicles.find(skin => skin.isRecommended === true);

	// Get the value of the 'amount' property if the object is found
    	let skinId = null;
    	if (skinRecommended) {
        	skinId = skinRecommended.id;
    	}


    	// Log the amount value
    	console.log(inventory);
	console.log("Amount with Quality 10:", weaponAmount);
	console.log("IDrecommended:", skinId);

	if(energya > energyuse && weaponAmount > 2){
		const fightDeployPayload = constructPayloadForFightDeploy(target, zonetarget, countryLocationId, weaponQuality, energyuse, skinId, _token);
    		const fightDeployResponse = await sendPostRequestForFightDeploy(fightDeployPayload);
		console.log(fightDeployResponse);
		await delay(10000); // 1000 milliseconds = 1 second
	}

	await delay(1000); // 1000 milliseconds = 1 second
    }
}

// Add an event listener for page load
    window.addEventListener('load', function() {
        // Call the main function when the page is fully loaded
        main();
    });
})();