alt-svc: h3=":443"; ma=86400
cf-ray: 8f6a9f22a761963b-kix
connection: keep-alive
content-length: 18
content-type: text/plain;charset=utf-8
date: mon, 23 dec 2024 19:05:10 gmt
nel: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
report-to: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v4?s=ol37axxfj0u%2fh7tjzbh3ibhhdfb4qf7zddkyrjpgqtca20mhngfly5fot6k6jas6pxpl0swlpxpxrrvr5pg3ujvhivuqexwawvvt7m5%2b7v76ithnfbdvvwilslw7%2b6qi7te4b1tha92jysd%2fdqg%2ba5llvdtfhqfxfy3qiffqoutpgpytlf3ovoxylw%3d%3d"}],"group":"cf-nel","max_age":604800}
server: cloudflare
server-timing: cfl4;desc="?proto=tcp&rtt=591&min_rtt=579&rtt_var=186&sent=5&recv=8&lost=0&retrans=0&sent_bytes=3029&recv_bytes=4019&delivery_rate=4747540&cwnd=159&unsent_bytes=0&cid=4c0a9db7382acd74&ts=14&x=0"
vary: accept-encodingبرای کدconst TELEGRAM_BOT_TOKEN = '<TRUFFLEHOG_REDACTED_TELEGRAMBOTTOKEN>';
const TELEGRAM_API_URL = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}`;

const CRYPTO_API_URL = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false';

const messages = {
    'fa': {
        welcome: "به ربات سیگنال ارز دیجیتال خوش آمدید! زبان خود را انتخاب کنید.",
        signal: "سیگنال برای {name} ({symbol}):\n🔹 قیمت ورود: ${entry}\n🔹 قیمت هدف: ${target} (${percentage}%)\n🔹 حد ضرر: ${stopLoss}\n",
        chooseLanguage: "لطفاً زبان خود را انتخاب کنید: /setlang fa برای فارسی، /setlang en برای انگلیسی، /setlang es برای اسپانیایی، /setlang fr برای فرانسوی، /setlang de برای آلمانی."
    },
    'en': {
        welcome: "Welcome to the Crypto Signal Bot! Please choose your language.",
        signal: "Signal for {name} ({symbol}):\n🔹 Entry price: ${entry}\n🔹 Target price: ${target} (${percentage}%)\n🔹 Stop loss: ${stopLoss}\n",
        chooseLanguage: "Please choose your language: /setlang fa for Persian, /setlang en for English, /setlang es for Spanish, /setlang fr for French, /setlang de for German."
    }
};

const userLanguages = {};

const cache = new Map(); // کش ساده برای داده‌های ارز دیجیتال

async function fetchTopCryptos() {
    if (cache.has('topCryptos')) {
        return cache.get('topCryptos');
    }

    const response = await fetch(CRYPTO_API_URL);
    const data = await response.json();

    cache.set('topCryptos', data);
    setTimeout(() => cache.delete('topCryptos'), 300000); // پاک کردن کش پس از 5 دقیقه

    return data;
}

async function handleRequest(request) {
    const { method } = request;

    if (method !== 'POST') {
        return new Response('Method Not Allowed', { status: 405 });
    }

    const update = await request.json();

    if (update.message) {
        const chatId = update.message.chat.id;
        const command = update.message.text;

        const language = userLanguages[chatId] || 'en';

        if (command === '/start') {
            await sendMessage(chatId, messages[language].welcome);
            await sendMessage(chatId, messages[language].chooseLanguage);
        } else if (command.startsWith('/setlang')) {
            const lang = command.split(' ')[1];
            if (messages[lang]) {
                userLanguages[chatId] = lang;
                await sendMessage(chatId, `Language set to ${lang}`);
            } else {
                await sendMessage(chatId, "Invalid language!");
            }
        } else if (command === '/getsignals') {
            const signals = await generateSignals(language);
            await sendMessage(chatId, signals);
        } else {
            await sendMessage(chatId, "Unknown command! Please use /start or /getsignals.");
        }
    }

    return new Response('OK', { status: 200 });
}

async function generateSignals(language) {
    const topCryptos = await fetchTopCryptos();

    const signals = topCryptos.slice(0, 5).map(crypto => {
        const entryPrice = crypto.current_price;
        const targetPrice = entryPrice * (1 + (Math.random() * 0.1));
        const stopLossPrice = entryPrice * (1 - (Math.random() * 0.1));
        const percentage = ((targetPrice - entryPrice) / entryPrice) * 100;

        return {
            name: crypto.name,
            symbol: crypto.symbol,
            entry: entryPrice.toFixed(2),
            target: targetPrice.toFixed(2),
            stopLoss: stopLossPrice.toFixed(2),
            percentage: percentage.toFixed(2),
        };
    });

    return formatSignals(signals, language);
}

function formatSignals(signals, language) {
    return signals.map(signal => (
        messages[language].signal.replace('{name}', signal.name)
                                  .replace('{symbol}', signal.symbol.toUpperCase())
                                  .replace('${entry}', signal.entry)
                                  .replace('${target}', signal.target)
                                  .replace('${percentage}', signal.percentage)
                                  .replace('${stopLoss}', signal.stopLoss)
    )).join('\n');
}

async function sendMessage(chatId, text) {
    await fetch(`${TELEGRAM_API_URL}/sendMessage`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ chat_id: chatId, text }),
    });
}

addEventListener('fetch', event => {
    event.respondWith(handleRequest(event.request));
});
آمده خطا درست کن برام ارسال کن