package services import ( "bytes" "encoding/json" "fmt" "net/http" "os" ) type TelegramService struct { BotToken string } type TelegramMessage struct { ChatID interface{} `json:"chat_id"` Text string `json:"text"` ParseMode string `json:"parse_mode"` } func NewTelegramService() *TelegramService { botToken := os.Getenv("TELEGRAM_BOT_TOKEN") if botToken == "" { fmt.Println("Warning: TELEGRAM_BOT_TOKEN not set in environment variables") } return &TelegramService{BotToken: botToken} } func (ts *TelegramService) SendMessage(chatID interface{}, message string) error { if ts.BotToken == "" { return fmt.Errorf("Telegram bot token is not configured") } apiURL := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", ts.BotToken) telegramMessage := TelegramMessage{ ChatID: chatID, Text: message, ParseMode: "HTML", } jsonData, err := json.Marshal(telegramMessage) if err != nil { return fmt.Errorf("error marshalling request body: %v", err) } resp, err := http.Post(apiURL, "application/json", bytes.NewBuffer(jsonData)) if err != nil { return fmt.Errorf("error sending request to Telegram API: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("received non-OK response from Telegram API: %d", resp.StatusCode) } return nil } // GetBotUsername obtiene el username (@nombre) del bot a partir de su token. func GetBotUsername(botToken string) string { if botToken == "" { return "" } resp, err := http.Get(fmt.Sprintf("https://api.telegram.org/bot%s/getMe", botToken)) if err != nil { return "" } defer resp.Body.Close() var result struct { OK bool `json:"ok"` Result struct { Username string `json:"username"` } `json:"result"` } if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { return "" } return result.Result.Username } // SendMessageWithToken envía un mensaje usando un bot token explícito (útil para notificar a usuarios con su propio chat_id). func (ts *TelegramService) SendMessageWithToken(chatID interface{}, message, botToken string) error { svc := &TelegramService{BotToken: botToken} return svc.SendMessage(chatID, message) }