59 lines
1.3 KiB
Go
59 lines
1.3 KiB
Go
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
|
|
}
|