PP Alert Price TELE

Plays chicken sound and/or sends Telegram alert based on price thresholds, logs the difference every second

// ==UserScript==
// @name         PP Alert Price TELE
// @description  Plays chicken sound and/or sends Telegram alert based on price thresholds, logs the difference every second
// @version      1.7.1
// @include      https://*/game.php*screen=market&mode=exchange*
// @namespace    https://greasyfork.org/users/151096
// ==/UserScript==

let lastSoundTime = 0;
let lastTelegramTime = 0;
let lastCaptchaAlertTime = 0;

// Load saved settings
let lowerLimit = localStorage.getItem('ppAlertLowerLimit') ? parseInt(localStorage.getItem('ppAlertLowerLimit')) : 1000;
let upperLimit = localStorage.getItem('ppAlertUpperLimit') ? parseInt(localStorage.getItem('ppAlertUpperLimit')) : 3000;
let chatId = localStorage.getItem('telegramChatId') || "0";
let soundAlertEnabled = localStorage.getItem('soundAlertEnabled') === 'true';
let telegramAlertEnabled = localStorage.getItem('telegramAlertEnabled') === 'true';

const botToken = "YOUR_BOT_TOKEN_HERE";

// Function to send message to Telegram bot
function sendToTelegram(location, woodPrice, stonePrice, ironPrice) {
    if (!telegramAlertEnabled) return;
    const message = `Location: ${location}; Wood: ${woodPrice}; Clay: ${stonePrice}; Iron: ${ironPrice}`;
    const url = `https://api.telegram.org/bot${botToken}/sendMessage?chat_id=${chatId}&text=${encodeURIComponent(message)}`;

    fetch(url)
        .then(response => {
            if (!response.ok) {
                console.error("Failed to send message to Telegram:", response.statusText);
            } else {
                console.log("Message sent to Telegram:", message);
            }
        })
        .catch(error => console.error("Telegram API error:", error));
}

// Function to send CAPTCHA alert
function sendCaptchaAlert() {
    const url = `https://api.telegram.org/bot${botToken}/sendMessage?chat_id=${chatId}&text=${encodeURIComponent("Ada CAPTCHA atau Bot Protection!")}`;

    fetch(url)
        .then(response => {
            if (!response.ok) {
                console.error("Failed to send CAPTCHA alert to Telegram:", response.statusText);
            } else {
                console.log("CAPTCHA alert sent to Telegram");
            }
        })
        .catch(error => console.error("Telegram API error:", error));
}

// Create settings button
const settingsBtn = document.createElement('button');
settingsBtn.innerText = 'PP Alert Settings';
settingsBtn.style.position = 'fixed';
settingsBtn.style.top = '20px';
settingsBtn.style.right = '20px';
settingsBtn.style.zIndex = '1000';
document.body.appendChild(settingsBtn);

// Create settings popup
const settingsPopup = document.createElement('div');
settingsPopup.style.display = 'none';
settingsPopup.style.position = 'fixed';
settingsPopup.style.top = '50px';
settingsPopup.style.right = '50px';
settingsPopup.style.backgroundColor = '#f9f9f9';
settingsPopup.style.padding = '20px';
settingsPopup.style.border = '1px solid #ddd';
settingsPopup.innerHTML = `
    <label>Chat ID: <input type="text" id="chatIdInput" value="${chatId}"></label><br><br>
    <label>Lower Limit: <input type="number" id="lowerLimitInput" value="${lowerLimit}"></label><br>
    <label>Upper Limit: <input type="number" id="upperLimitInput" value="${upperLimit}"></label><br><br>
    <label><input type="checkbox" id="soundAlertCheckbox" ${soundAlertEnabled ? 'checked' : ''}> Enable Chicken Sound Alert</label><br>
    <label><input type="checkbox" id="telegramAlertCheckbox" ${telegramAlertEnabled ? 'checked' : ''}> Enable Telegram Alert</label><br><br>
    <button id="saveSettingsBtn">Save Settings</button><br><br>
`;
document.body.appendChild(settingsPopup);

// Toggle settings popup
settingsBtn.addEventListener('click', () => {
    settingsPopup.style.display = settingsPopup.style.display === 'none' ? 'block' : 'none';
});

// Save settings
document.getElementById('saveSettingsBtn').addEventListener('click', () => {
    chatId = document.getElementById('chatIdInput').value;
    lowerLimit = parseInt(document.getElementById('lowerLimitInput').value);
    upperLimit = parseInt(document.getElementById('upperLimitInput').value);
    soundAlertEnabled = document.getElementById('soundAlertCheckbox').checked;
    telegramAlertEnabled = document.getElementById('telegramAlertCheckbox').checked;

    // Save to local storage
    localStorage.setItem('telegramChatId', chatId);
    localStorage.setItem('ppAlertLowerLimit', lowerLimit);
    localStorage.setItem('ppAlertUpperLimit', upperLimit);
    localStorage.setItem('soundAlertEnabled', soundAlertEnabled);
    localStorage.setItem('telegramAlertEnabled', telegramAlertEnabled);

    settingsPopup.style.display = 'none';
    alert("Settings saved successfully!");
});

// Check prices and send alerts
setInterval(() => {
    const woodPrice = parseInt(document.getElementById("premium_exchange_rate_wood")?.textContent || 0);
    const stonePrice = parseInt(document.getElementById("premium_exchange_rate_stone")?.textContent || 0);
    const ironPrice = parseInt(document.getElementById("premium_exchange_rate_iron")?.textContent || 0);
    const currentTime = Date.now();
    const location = document.querySelector('td.box-item b.nowrap')?.textContent || "Unknown";

    // Check conditions and send alert
    if ((woodPrice < lowerLimit || stonePrice < lowerLimit || ironPrice < lowerLimit ||
        woodPrice > upperLimit || stonePrice > upperLimit || ironPrice > upperLimit) &&
        (currentTime - lastSoundTime >= 30000)) {

        if (soundAlertEnabled) TribalWars.playSound("chicken");
        sendToTelegram(location, woodPrice, stonePrice, ironPrice);
        lastSoundTime = currentTime;
    }

    // Check for CAPTCHA iframe or #bot_check div and send alert if needed
    const captchaIframe = document.querySelector('iframe[src*="hcaptcha"]');
    const botCheckDiv = document.getElementById("bot_check");

    if ((captchaIframe || botCheckDiv) && (currentTime - lastCaptchaAlertTime >= 300000)) {  // 5 minutes
        console.log("Ada CAPTCHA atau Bot Protection");
        sendCaptchaAlert();
        lastCaptchaAlertTime = currentTime;
    }
}, 1000);  // Check every second