Created
October 19, 2024 10:25
-
-
Save deifos/9d144f822921d9e93e7cee72d4de4eda to your computer and use it in GitHub Desktop.
Service to send events to a Telelelgram bot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import TelegramBot from "node-telegram-bot-api"; | |
//TODO: Add a way to track events in a database right now I'm lazy. | |
export interface TelegramEventTrackerConfig { | |
botToken: string; | |
chatId: string; | |
} | |
type PrimitiveType = string | number | boolean; | |
export interface EventData { | |
[key: string]: PrimitiveType | PrimitiveType[] | null | undefined; | |
} | |
export class TelegramEventTracker { | |
private static instance: TelegramEventTracker | null = null; | |
private bot: TelegramBot; | |
private chatId: string; | |
private constructor(config: TelegramEventTrackerConfig) { | |
if (!config.botToken || !config.chatId) { | |
throw new Error("Bot token and chat ID are required"); | |
} | |
this.bot = new TelegramBot(config.botToken, { polling: false }); | |
this.chatId = config.chatId; | |
} | |
public static getInstance(): TelegramEventTracker { | |
if (!TelegramEventTracker.instance) { | |
const config: TelegramEventTrackerConfig = { | |
botToken: process.env.TELEGRAM_BOT_TOKEN as string, | |
chatId: process.env.TELEGRAM_CHAT_ID as string, | |
}; | |
TelegramEventTracker.instance = new TelegramEventTracker(config); | |
} | |
return TelegramEventTracker.instance; | |
} | |
async trackEvent(eventName: string, eventData: EventData): Promise<void> { | |
const message = formatEventMessage(eventName, eventData); | |
try { | |
await this.bot.sendMessage(this.chatId, message); | |
} catch (error) { | |
console.error( | |
`Failed to send Telegram notification for event ${eventName}:`, | |
error | |
); | |
throw new Error( | |
`Failed to send Telegram notification: ${(error as Error).message}` | |
); | |
} | |
} | |
} | |
function formatEventMessage(eventName: string, eventData: EventData): string { | |
let message = `New Event: ${eventName}\n\nDetails:`; | |
for (const [key, value] of Object.entries(eventData)) { | |
message += `\n${key}: ${formatValue(value)}`; | |
} | |
return message; | |
} | |
function formatValue(value: EventData[string]): string { | |
if (Array.isArray(value)) { | |
return value.map(formatValue).join(", "); | |
} | |
if (value === null || value === undefined) { | |
return "N/A"; | |
} | |
return String(value); | |
} | |
export const eventTracker = TelegramEventTracker.getInstance(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment