-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram.go
41 lines (35 loc) · 890 Bytes
/
telegram.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
type SendMessageRequest struct {
ChatID int64 `json:"chat_id"`
Text string `json:"text"`
ParseMode string `json:"parse_mode,omitempty"`
}
func sendTelegramMessage(token string, chatID int64, text string) error {
const telegramAPIURL = "https://api.telegram.org/bot"
url := fmt.Sprintf("%s%s/sendMessage", telegramAPIURL, token)
requestBody, err := json.Marshal(&SendMessageRequest{
ChatID: chatID,
Text: text,
ParseMode: "Markdown", // or "HTML", if you want
})
if err != nil {
return err
}
resp, err := http.Post(url, "application/json", bytes.NewBuffer(requestBody))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed sending message: %s", body)
}
return nil
}