Torn Combat Logger with API Integration

Logs combat events and integrates Torn API data

Tính đến 14-10-2024. Xem phiên bản mới nhất.

// ==UserScript==
// @name         Torn Combat Logger with API Integration
// @namespace    http://torn.com/
// @version      1.7
// @description  Logs combat events and integrates Torn API data
// @author       Quanna_Parker
// @match        https://www.torn.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Add your Torn API key here
    const apiKey = "ADD_API_KEY"; // Replace with your actual API key

    // Initialize an array to store combat logs
    let combatLogs = JSON.parse(localStorage.getItem("combatLogs")) || [];

    // Max number of logs before auto-cleanup
    const maxLogs = 100;

    // Function to fetch Torn user data
    function fetchTornUserData(userId) {
        const url = `https://api.torn.com/user/${userId}?selections=&key=${apiKey}`;

        fetch(url)
            .then(response => response.json())
            .then(data => {
                console.log('Torn User Data:', data);
                // You can optionally use this data in the logger or UI
            })
            .catch(error => console.error('Error fetching Torn data:', error));
    }

    // Function to log combat events
    function logCombat(eventDetails) {
        const logEntry = {
            time: new Date().toLocaleString(),
            attacker: eventDetails.attacker,
            attackerId: eventDetails.attackerId, // Assuming this ID is available from eventDetails
            damage: eventDetails.damage,
            result: eventDetails.result,
            attackType: eventDetails.attackType,
            yourHealthBefore: eventDetails.yourHealthBefore,
            yourHealthAfter: eventDetails.yourHealthAfter
        };

        // Add the new log to the logs array
        combatLogs.push(logEntry);

        // Fetch attacker details from the Torn API
        fetchTornUserData(eventDetails.attackerId);

        // Auto-cleanup: Remove the oldest log if exceeding maxLogs
        if (combatLogs.length > maxLogs) {
            combatLogs.shift();
        }

        // Save logs to local storage
        localStorage.setItem("combatLogs", JSON.stringify(combatLogs));
        console.log("Combat logged: ", logEntry);
    }

    // Function to monitor combat events on the page
    function monitorCombatEvents() {
        document.addEventListener('DOMContentLoaded', function() {
            const eventSection = document.querySelector("#events");

            if (eventSection) {
                let events = eventSection.querySelectorAll(".event");

                events.forEach(event => {
                    if (event.textContent.includes("attacked")) {
                        // Parse event details (adjust this based on Torn's actual event structure)
                        let attacker = event.querySelector(".attacker")?.textContent || "Unknown";
                        let attackerId = event.querySelector(".attacker")?.getAttribute('data-id') || "Unknown"; // Assuming an ID attribute is available
                        let damage = event.querySelector(".damage")?.textContent || "0";
                        let result = event.querySelector(".result")?.textContent || "N/A";
                        let attackType = event.querySelector(".attack-type")?.textContent || "N/A";
                        let yourHealthBefore = event.querySelector(".health-before")?.textContent || "N/A";
                        let yourHealthAfter = event.querySelector(".health-after")?.textContent || "N/A";

                        // Log the combat and fetch additional data from Torn API
                        logCombat({ attacker, attackerId, damage, result, attackType, yourHealthBefore, yourHealthAfter });
                    }
                });
            }
        });
    }

    // Call the function to start monitoring combat events
    monitorCombatEvents();

    // Function to create a pop-up to view combat logs
    function viewLogs() {
        let logWindow = document.createElement('div');
        logWindow.style.position = 'fixed';
        logWindow.style.top = '50px';
        logWindow.style.right = '50px';
        logWindow.style.width = '400px';
        logWindow.style.height = '400px';
        logWindow.style.backgroundColor = 'white';
        logWindow.style.border = '1px solid black';
        logWindow.style.zIndex = 1000;
        logWindow.style.overflowY = 'scroll';
        logWindow.style.padding = '10px';
        logWindow.style.boxShadow = '0px 0px 10px rgba(0, 0, 0, 0.5)';
        logWindow.style.borderRadius = '10px';

        // Close button
        let closeButton = document.createElement('button');
        closeButton.innerHTML = 'Close';
        closeButton.style.float = 'right';
        closeButton.onclick = function() {
            document.body.removeChild(logWindow);
        };

        let logContent = document.createElement('div');
        logWindow.appendChild(closeButton);
        logWindow.appendChild(logContent);

        document.body.appendChild(logWindow);

        // Display combat logs
        let logsHTML = '<h3>Combat Logs</h3>';
        combatLogs.forEach(log => {
            logsHTML += `<p><strong>Time:</strong> ${log.time}<br/>
                         <strong>Attacker:</strong> ${log.attacker}<br/>
                         <strong>Damage:</strong> ${log.damage}<br/>
                         <strong>Result:</strong> ${log.result}<br/>
                         <strong>Attack Type:</strong> ${log.attackType}<br/>
                         <strong>Your Health (Before):</strong> ${log.yourHealthBefore}<br/>
                         <strong>Your Health (After):</strong> ${log.yourHealthAfter}</p><hr/>`;
        });
        logContent.innerHTML = logsHTML;
    }

    // Function to add a button to view combat logs
    function addCombatLogsButton() {
        const existingDropdown = document.querySelector(".dropdown"); // Modify this selector as needed for Torn PDA

        if (existingDropdown) {
            const logsMenuItem = document.createElement('li');
            logsMenuItem.innerHTML = '<a href="#" id="combat-logs-menu">View Combat Logs</a>';
            existingDropdown.appendChild(logsMenuItem);

            logsMenuItem.onclick = function() {
                viewLogs();
            };
            console.log('Combat Logs button added.');
        }
    }

    // Add the button to the dropdown menu after the DOM is fully loaded
    window.onload = function() {
        addCombatLogsButton();
    };
})();