File size: 3,646 Bytes
2dddd1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const channelUsername = 'iraqborsa';
let currentIqdRate: number | null = null;
let currentRmbRate: number | null = null;

export async function initTelegramAuth() {
    console.log('Initializing Rates Fetchers...');
    
    // Initial fetch
    await Promise.all([
        fetchLatestRate(),
        fetchFrankfurterRates()
    ]);

    // Fetch rate every 24 hours
    setInterval(() => {
        fetchLatestRate();
        fetchFrankfurterRates();
    }, 24 * 60 * 60 * 1000);
}

export async function fetchLatestRate() {
    try {
        console.log(`Fetching latest messages from https://t.me/s/${channelUsername}...`);
        
        const response = await fetch(`https://t.me/s/${channelUsername}`);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const html = await response.text();
        
        const regex = /<div class="tgme_widget_message_text[^>]*>(.*?)<\/div>/g;
        let match;
        const messages: string[] = [];
        
        while ((match = regex.exec(html)) !== null) {
            // Strip HTML tags and decode basic entities if needed
            // Telegram usually escapes <, >, & and uses <br/> for newlines
            const textContent = match[1].replace(/<[^>]+>/g, ' ').replace(/&#036;/g, '$');
            messages.push(textContent);
        }
        
        // Telegram preview shows oldest to newest, so we check from the end
        const rateRegex = /100\$\s*=\s*(\d{2,3})[,.]?(\d{3})/;
        
        for (let i = messages.length - 1; i >= 0; i--) {
            const text = messages[i];
            const matchRate = text.match(rateRegex);
            
            if (matchRate) {
                // e.g., ["100$=153,700", "153", "700"] or ["100$=153700", "153", "700"]
                const valueStr = matchRate[1] + matchRate[2];
                const iqdPer100Usd = parseInt(valueStr, 10);
                const iqdPer1Usd = iqdPer100Usd / 100;
                
                currentIqdRate = iqdPer1Usd;
                console.log(`✅ Extracted new USD/IQD rate: 1 USD = ${iqdPer1Usd} IQD`);
                return;
            }
        }
        
        console.log('Could not find a valid rate in the recent messages.');
    } catch (error) {
        console.error('Failed to fetch from Telegram web preview:', error);
    }
}

export async function fetchFrankfurterRates() {
    try {
        console.log('Fetching latest rates from Frankfurter API...');
        const response = await fetch('https://api.frankfurter.app/latest?from=USD&to=CNY');
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data: any = await response.json();
        
        if (data.rates && data.rates.CNY) {
            currentRmbRate = data.rates.CNY;
            console.log(`✅ Extracted new USD/RMB rate: 1 USD = ${currentRmbRate!.toFixed(4)} RMB`);
        } else {
             console.log('Could not find a valid rate in Frankfurter API response.', data);
        }
    } catch (error) {
         console.error('Failed to fetch from Frankfurter API:', error);
    }
}

export function getCurrentRates() {
    return {
        USD: 1,
        IQD: currentIqdRate || 1500, // Fallback if telegram fails
        RMB: currentRmbRate || 7.2 // Fallback if fixer fails
    };
}

if (require.main === module) {
    initTelegramAuth().then(() => {
        console.log("Setup complete! You can press Ctrl+C to exit and start the main server.");
        // Process will keep running due to setInterval
    }).catch(console.error);
}