package notifier import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "time" "naviwatcher/internal/config" ) // Sender delivers a notification message to a destination (e.g. Telegram). // It is an interface so the real HTTP bot can be swapped for a stub in tests. type Sender interface { Send(ctx context.Context, message string) error } // telegramSender sends messages via the Telegram Bot API sendMessage method. type telegramSender struct { httpClient *http.Client token string chatID string baseURL string } // NewTelegramSender constructs a Sender that posts to the Telegram Bot API // using the token and chat ID from the given TelegramConfig. func NewTelegramSender(cfg config.TelegramConfig) *telegramSender { return &telegramSender{ httpClient: &http.Client{Timeout: 30 * time.Second}, token: cfg.Token, chatID: cfg.ChatID, baseURL: "https://api.telegram.org", } } // sendMessageRequest is the JSON payload for the Telegram sendMessage endpoint. type sendMessageRequest struct { ChatID string `json:"chat_id"` Text string `json:"text"` DisableWebPagePreview bool `json:"disable_web_page_preview"` } // Send posts the message to the configured Telegram chat. It returns an error // if the request cannot be built/sent or the API responds with a non-2xx code. func (s *telegramSender) Send(ctx context.Context, message string) error { payload := sendMessageRequest{ ChatID: s.chatID, Text: message, DisableWebPagePreview: true, } body, err := json.Marshal(payload) if err != nil { return fmt.Errorf("marshal telegram payload: %w", err) } url := fmt.Sprintf("%s/bot%s/sendMessage", s.baseURL, s.token) req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if err != nil { return fmt.Errorf("build telegram request: %w", err) } req.Header.Set("Content-Type", "application/json") resp, err := s.httpClient.Do(req) if err != nil { return fmt.Errorf("send telegram message: %w", err) } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) return fmt.Errorf("telegram API returned status %d: %s", resp.StatusCode, string(respBody)) } return nil }