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 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 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);
})();