import { BaseCommand } from '@adonisjs/core/ace' import type { CommandOptions } from '@adonisjs/core/types/ace' import { TelegramService } from '#services/telegram_service' import logger from '@adonisjs/core/services/logger' /** * Command to start Telegram bot * * Usage: * node ace telegram:start * * This command runs as a long-lived process and handles graceful shutdown. */ export default class StartTelegramBot extends BaseCommand { static commandName = 'telegram:start' static description = 'Start the Telegram bot for auction notifications' static options: CommandOptions = { startApp: true, staysAlive: true, } private telegramService: TelegramService | null = null async run() { try { this.logger.info('Initializing Telegram bot service...') // Get singleton instance this.telegramService = TelegramService.getInstance() // Setup graceful shutdown handlers this.setupShutdownHandlers() // Start the bot this.logger.info('Starting Telegram bot...') await this.telegramService.start() this.logger.success('Telegram bot is running! Press Ctrl+C to stop.') } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error) this.logger.error(`Failed to start Telegram bot: ${errorMsg}`) logger.error('Telegram bot startup failed', { error: errorMsg }) this.exitCode = 1 await this.terminate() } } /** * Setup handlers for graceful shutdown */ private setupShutdownHandlers(): void { const shutdown = async (signal: string) => { this.logger.info(`Received ${signal}, shutting down gracefully...`) if (this.telegramService) { try { await this.telegramService.stop() this.logger.success('Telegram bot stopped successfully') } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error) this.logger.error(`Error during shutdown: ${errorMsg}`) logger.error('Telegram bot shutdown error', { error: errorMsg }) } } await this.terminate() } // Handle SIGINT (Ctrl+C) process.on('SIGINT', () => shutdown('SIGINT')) // Handle SIGTERM (kill command) process.on('SIGTERM', () => shutdown('SIGTERM')) } /** * Command termination handler */ async completed() { if (this.telegramService && this.telegramService.getIsRunning()) { this.logger.info('Stopping Telegram bot...') await this.telegramService.stop() } } }