78 lines
2 KiB
Go
78 lines
2 KiB
Go
package main
|
||
|
||
import (
|
||
"bytes"
|
||
"encoding/json"
|
||
"fmt"
|
||
"io"
|
||
"log"
|
||
"net/http"
|
||
"net/url"
|
||
)
|
||
|
||
// telegramSendHTML отправляет HTML-сообщение в Telegram
|
||
func telegramSendHTML(message string) error {
|
||
if !isTelegramConfigured() {
|
||
log.Printf("[Telegram] Не настроен. Сообщение:\n%s\n", message)
|
||
return fmt.Errorf("telegram не настроен")
|
||
}
|
||
|
||
type tgMessage struct {
|
||
ChatID string `json:"chat_id"`
|
||
Text string `json:"text"`
|
||
ParseMode string `json:"parse_mode"`
|
||
}
|
||
|
||
msg := tgMessage{
|
||
ChatID: cfgTelegramChatID,
|
||
Text: message,
|
||
ParseMode: "HTML",
|
||
}
|
||
|
||
jsonData, err := json.Marshal(msg)
|
||
if err != nil {
|
||
return fmt.Errorf("marshal error: %w", err)
|
||
}
|
||
|
||
apiURL := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", cfgTelegramBotToken)
|
||
|
||
resp, err := http.Post(apiURL, "application/json", bytes.NewBuffer(jsonData))
|
||
if err != nil {
|
||
return fmt.Errorf("http error: %w", err)
|
||
}
|
||
defer resp.Body.Close()
|
||
|
||
if resp.StatusCode != http.StatusOK {
|
||
body, _ := io.ReadAll(resp.Body)
|
||
return fmt.Errorf("telegram api error: status %d, body: %s", resp.StatusCode, string(body))
|
||
}
|
||
|
||
return nil
|
||
}
|
||
|
||
// telegramSendPlainText отправляет текстовое сообщение без форматирования
|
||
func telegramSendPlainText(message string) error {
|
||
if !isTelegramConfigured() {
|
||
log.Printf("[Telegram] Не настроен. Сообщение:\n%s\n", message)
|
||
return fmt.Errorf("telegram не настроен")
|
||
}
|
||
|
||
apiURL := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", cfgTelegramBotToken)
|
||
|
||
data := url.Values{}
|
||
data.Set("chat_id", cfgTelegramChatID)
|
||
data.Set("text", message)
|
||
|
||
resp, err := http.PostForm(apiURL, data)
|
||
if err != nil {
|
||
return fmt.Errorf("http error: %w", err)
|
||
}
|
||
defer resp.Body.Close()
|
||
|
||
if resp.StatusCode != http.StatusOK {
|
||
body, _ := io.ReadAll(resp.Body)
|
||
return fmt.Errorf("telegram api error: status %d, body: %s", resp.StatusCode, string(body))
|
||
}
|
||
|
||
return nil
|
||
}
|