import { initializeBot } from "./botManager"; import { telegrafBots } from "../models"; import { supabase } from "../db/supabase"; import { createLogger } from "../utils/logger"; import { setupPaymentWebhookHandlers } from './handlers/paymentWebhookHandlers'; import { getBotIdFromToken, isValidBotToken } from "../utils/botUtils"; const logger = createLogger('BotManager'); // Utility function to update bot status in database const updateBotStatus = async (botId: string, isActive: boolean, error?: string) => { try { await supabase .from('bots') .update({ is_active: isActive, last_activity: new Date().toISOString(), state: { status: isActive ? 'running' : 'error', startedAt: isActive ? new Date().toISOString() : undefined, error: error } }) .eq('id', botId); } catch (error: any) { logger.error(`Error updating bot status: ${error.message}`); } }; export const handleAddTelegrafBot = async (botId: string) => { if (!botId) { return { status: 400, data: { error: "Bot ID is required" } }; } try { logger.info(`Fetching bot data for bot ID: ${botId}`); // Fetch bot data from database const { data: botData, error } = await supabase .from('bots') .select('*') .eq('id', botId) .single(); if (error) { logger.error(`Error fetching bot data: ${error.message}`); return { status: 404, data: { error: `Bot not found: ${error.message}` } }; } if (!botData || !botData.bot_token) { return { status: 404, data: { error: "Bot token not found in database" } }; } // Validate bot token format if (!isValidBotToken(botData.bot_token)) { logger.error(`Invalid bot token format for bot ${botId}`); return { status: 400, data: { error: "Invalid bot token format" } }; } // Check if bot is already running if (telegrafBots.has(botData.bot_token)) { return { status: 200, data: { error: "Bot is already running" } }; } try { // Initialize the bot with settings from database const result = await initializeBot(botData.bot_token, botData); if (result.success && result.bot) { // Store the bot instance in the map telegrafBots.set(botData.bot_token, result.bot); try { // Update bot status to active await updateBotStatus(botId, true); logger.info(`Bot ${botData.name} (${botId}) launched successfully`); await result.bot.launch(); // Setup payment webhook handlers // setupPaymentWebhookHandlers(result.bot); return { status: 200, data: { message: result.message, bot: { id: botData.id, name: botData.name, is_active: true } }}; } catch (error: any) { logger.error(`Error launching bot: ${error.message}`); await updateBotStatus(botId, false, error.message); return { status: 500, data: { error: `Error launching bot: ${error.message}` } }; } } else { logger.error(`Error initializing bot: ${result.message}`); await updateBotStatus(botId, false, result.message); return { status: 500, data: { error: result.message } }; } } catch (error: any) { logger.error(`Bot initialization error: ${error.message}`); await updateBotStatus(botId, false, error.message); return { status: 500, data: { error: `Bot initialization error: ${error.message}` } }; } } catch (error: any) { logger.error(`Unexpected error: ${error.message}`); await updateBotStatus(botId, false, error.message); return { status: 500, data: { error: `Unexpected error: ${error.message}` } }; } };