-
Notifications
You must be signed in to change notification settings - Fork 0
/
telegram.go
61 lines (50 loc) · 1.23 KB
/
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"strings"
)
const TELEGRAM_API = "https://api.telegram.org/bot%s/sendMessage"
type TelegramLogger struct {
url string
chatID string
email string
client *http.Client
}
func NewTelegramLogger(token string, chatID string) (*TelegramLogger, error) {
client, err := NewTimeoutClient()
if err != nil {
return nil, err
}
return &TelegramLogger{
url: fmt.Sprintf(TELEGRAM_API, token),
chatID: chatID,
client: client,
}, nil
}
func (s *TelegramLogger) Logf(format string, args ...interface{}) {
text := fmt.Sprintf("%s", fmt.Sprintf(format, args...))
data := url.Values{}
data.Add("chat_id", s.chatID)
data.Add("text", text)
req, err := http.NewRequest("POST", s.url, strings.NewReader(data.Encode()))
if err != nil {
log.Printf("failed to create request: %v\n", err)
return
}
req.Header.Set("content-length", strconv.Itoa(len(data.Encode())))
req.Header.Set("content-type", "application/x-www-form-urlencoded")
resp, err := s.client.Do(req)
if err != nil {
log.Printf("failed to make request: %v\n", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Printf("failed to get response: %v\n", resp)
return
}
}