wallets-api / server /src /telegram.ts
z1amez's picture
v.1
2dddd1f
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);
}