Torn Trade Notification

Notifies when a user adds items to a trade

目前為 2024-02-14 提交的版本,檢視 最新版本

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         Torn Trade Notification
// @namespace    http://tampermonkey.net/
// @version      2
// @description  Notifies when a user adds items to a trade
// @author       Weav3r
// @match        https://www.torn.com/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_registerMenuCommand
// ==/UserScript==

(function() {
    'use strict';

    GM_registerMenuCommand("Set API Key", function() {
        var apiKey = prompt("Please enter your Torn API Key:", GM_getValue("apiKey", ""));
        if (apiKey) {
            GM_setValue("apiKey", apiKey);
            alert("API Key set successfully.");
        }
    }, "k");

    var apiKey = GM_getValue("apiKey");
    if (!apiKey) {
        console.warn("API Key is not set. Use the Tampermonkey menu to set your API Key.");
        return;
    }

    function fetchUserData(userId) {
        return new Promise(function(resolve) {
            var storedName = localStorage.getItem(`userName_${userId}`);
            if (storedName) {
                resolve(storedName);
                return;
            }

            fetch(`https://api.torn.com/user/${userId}?selections=basic&key=${apiKey}`)
                .then(response => response.json())
                .then(data => {
                    if (data && data.name) {
                        localStorage.setItem(`userName_${userId}`, data.name);
                        resolve(data.name);
                    } else {
                        resolve("Unknown");
                    }
                }).catch(() => resolve("Unknown"));
        });
    }

    function checkTrades() {
        if (new Date().getTime() - (parseInt(localStorage.getItem("lastApiCallTimestamp"), 10) || 0) >= 60000) {
            localStorage.setItem("lastApiCallTimestamp", new Date().getTime().toString());

            fetch(`https://api.torn.com/user/?selections=log&key=${apiKey}`)
                .then(response => response.json())
                .then(data => {
                    if (data.error) return;

                    // Mapping to keep track of completed trades.
                    let completedTradesMap = {};

                    // First, identify all completed trades.
                    Object.values(data.log).forEach(log => {
                        if (log.title === "Trade completed") {
                            const tradeIdMatch = log.data.trade_id.match(/ID=(\d+)/);
                            if (tradeIdMatch) {
                                completedTradesMap[tradeIdMatch[1]] = true;
                            }
                        }
                    });

                    // Retrieve and update notified timestamps.
                    let notifiedTimestamps = JSON.parse(localStorage.getItem("notifiedTimestamps") || "[]");

                    Object.values(data.log).forEach(log => {
                        const tradeIdMatch = log.data.trade_id.match(/ID=(\d+)/);
                        if (!tradeIdMatch) return;

                        let timestamp = log.timestamp.toString();
                        if (log.title === "Trade items add other user" && !completedTradesMap[tradeIdMatch[1]] && !notifiedTimestamps.includes(timestamp)) {
                            notifiedTimestamps.push(timestamp);
                            if (notifiedTimestamps.length > 100) notifiedTimestamps.shift();
                            localStorage.setItem("notifiedTimestamps", JSON.stringify(notifiedTimestamps));

                            fetchUserData(log.data.user).then(userName => {
                                GM_notification({
                                    title: "New Trade Item Added",
                                    text: `Items have been added to your trade with ${userName}. Click to view.`,
                                    image: 'https://www.torn.com/favicon.ico',
                                    onclick: function() {
                                        window.open(`https://www.torn.com/trade.php#step=view&ID=${tradeIdMatch[1]}`, '_blank');
                                    }
                                });
                            });
                        }
                    });
                }).catch(error => console.error("Error fetching trade data:", error));
        }
    }

    setInterval(checkTrades, 60000);
    checkTrades();
})();