Spaces:
Sleeping
Sleeping
| ; | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| exports.initTelegramAuth = initTelegramAuth; | |
| exports.fetchLatestRate = fetchLatestRate; | |
| exports.getCurrentRates = getCurrentRates; | |
| const channelUsername = 'iraqborsa'; | |
| let currentIqdRate = null; | |
| async function initTelegramAuth() { | |
| console.log('Initializing Telegram Rate Fetcher...'); | |
| // Initial fetch | |
| await fetchLatestRate(); | |
| // Fetch rate every 10 minutes | |
| setInterval(fetchLatestRate, 10 * 60 * 1000); | |
| } | |
| 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 = []; | |
| 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(/$/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); | |
| } | |
| } | |
| function getCurrentRates() { | |
| return { | |
| USD: 1, | |
| IQD: currentIqdRate || 1500, // Fallback if telegram fails | |
| RMB: 7.2 // Static for now, can be expanded | |
| }; | |
| } | |
| 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); | |
| } | |