freshyo/apps/backend/src/lib/telegram-service.ts
2026-06-27 08:30:59 +05:30

46 lines
1.5 KiB
TypeScript

import { getIsDevMode, getTelegramBotToken, getTelegramChatIds } from '@/src/lib/env-exporter'
export const sendTelegramMessage = async (message: string): Promise<boolean | null> => {
if (getIsDevMode()) {
return null;
}
const botToken = getTelegramBotToken()
const chatIds = getTelegramChatIds()
if (!botToken || chatIds.length === 0) {
console.warn('Telegram credentials not configured, skipping notification')
return null
}
const telegramApiUrl = `https://api.telegram.org/bot${botToken}`
try {
const results = await Promise.all(
chatIds.map(async (chatId) => {
try {
const response = await fetch(`${telegramApiUrl}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: chatId, text: message, parse_mode: 'HTML' }),
})
const data = await response.json() as { ok: boolean }
if (data.ok) {
console.log(`Telegram message sent successfully to ${chatId}`)
return true
} else {
console.error(`Telegram API error for ${chatId}:`, data)
return false
}
} catch (error) {
console.error(`Failed to send Telegram message to ${chatId}:`, error)
return false
}
})
)
console.log('sent telegram message successfully')
return results.some((result) => result)
} catch (error) {
console.error('Failed to send Telegram message:', error)
return false
}
}