Torn Faction Inventory Sum

Fetch and sum item quantities from the Torn API for a faction. Stores API key in local storage.

目前為 2025-02-01 提交的版本,檢視 最新版本

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         Torn Faction Inventory Sum
// @namespace    http://tornfactioninventorybyak.net/
// @version      1.2
// @description  Fetch and sum item quantities from the Torn API for a faction. Stores API key in local storage.
// @author       -A-K-[3455584]
// @license      MIT
// @match        https://www.torn.com/index.php    
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    const STORAGE_KEY = "tornApiKey";
    const categories = ["armor", "boosters", "caches", "cesium", "drugs", "medical", "temporary", "weapons"];

    async function fetchCategoryInventory(apiKey, category) {
        const url = `https://api.torn.com/faction/?selections=${category}&key=${apiKey}`;
        console.log(`🔄 Fetching data for category: ${category} from ${url}`);

        try {
            const response = await fetch(url);
            if (!response.ok) {
                console.error(`❌ Error: HTTP ${response.status} - ${response.statusText}`);
                return { category, quantity: 0 };
            }

            const data = await response.json();
            if (data.error) {
                console.error(`⚠️ API Error: ${data.error.error}`);
                return { category, quantity: 0 };
            }

            let totalQuantity = 0;
            if (data[category] && Array.isArray(data[category])) {
                data[category].forEach(item => {
                    totalQuantity += parseInt(item.quantity) || 0;
                    console.log(`   ➕ ${item.name}: ${item.quantity}`);
                });
            }

            console.log(`✅ Total for ${category}: ${totalQuantity}`);
            return { category, quantity: totalQuantity };

        } catch (error) {
            console.error("❌ Error fetching data:", error);
            return { category, quantity: 0 };
        }
    }

    async function fetchAndSumInventory(apiKey) {
        let totalSum = 0;
        let categoryTotals = [];

        for (const category of categories) {
            const result = await fetchCategoryInventory(apiKey, category);
            totalSum += result.quantity;
            categoryTotals.push(result);
            await new Promise(resolve => setTimeout(resolve, 1000)); // Delay to prevent rate limiting
        }

        displayResult(totalSum, categoryTotals);
    }

    function displayResult(totalQuantity, categoryTotals) {
        let resultDiv = document.getElementById("inventoryTotal");
        if (!resultDiv) {
            resultDiv = document.createElement("div");
            resultDiv.id = "inventoryTotal";
            resultDiv.style.padding = "10px";
            resultDiv.style.marginTop = "10px";
            resultDiv.style.background = "#1e1e1e";
            resultDiv.style.color = "#fff";
            resultDiv.style.borderRadius = "5px";
            document.getElementById("column1").appendChild(resultDiv);
        }

        let categoryText = categoryTotals.map(ct => `<li>${ct.category}: ${ct.quantity}</li>`).join("");
        resultDiv.innerHTML = `<strong>Total Quantity of Items:</strong> ${totalQuantity}<br><ul>${categoryText}</ul>`;
    }

    function getStoredApiKey() {
        return localStorage.getItem(STORAGE_KEY);
    }

    function saveApiKey(apiKey) {
        localStorage.setItem(STORAGE_KEY, apiKey);
    }

    function promptForApiKey() {
        let apiKey = prompt("🔑 Enter your Torn API key:");
        if (apiKey) {
            saveApiKey(apiKey);
            return apiKey;
        }
        return null;
    }

    function createFetchButton() {
        const container = document.getElementById("column1");
        if (!container) {
            console.warn("⚠️ Column1 div not found!");
            return;
        }

        const button = document.createElement("button");
        button.innerText = "Fetch Inventory Sum";
        button.style.padding = "8px 12px";
        button.style.marginTop = "10px";
        button.style.background = "#0078D7";
        button.style.color = "#fff";
        button.style.border = "none";
        button.style.borderRadius = "5px";
        button.style.cursor = "pointer";
        button.style.fontSize = "14px";
        button.style.display = "block";
        button.style.width = "100%";

        button.onclick = function () {
            let apiKey = getStoredApiKey();
            if (!apiKey) {
                apiKey = promptForApiKey();
            }

            if (apiKey) {
                fetchAndSumInventory(apiKey);
            }
        };

        container.appendChild(button);
    }

    setTimeout(createFetchButton, 2000);
})();