forked from projectdiscovery/notify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram.go
75 lines (63 loc) · 1.5 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package notify
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/projectdiscovery/retryablehttp-go"
)
// DefaultTelegraTimeout to conclude operations
const (
DefaultTelegraTimeout = 5 * time.Second
Endpoint = "https://api.telegram.org/bot{{apikey}}/sendMessage?chat_id={{chatid}}&text={{message}}"
)
// TelegramClient handling webhooks
type TelegramClient struct {
client *retryablehttp.Client
apiKEY string
chatID string
TimeOut time.Duration
}
// SendInfo to telegram
func (dc *TelegramClient) SendInfo(message string) (err error) {
return dc.sendHTTPRequest(message)
}
func (dc *TelegramClient) sendHTTPRequest(message string) error {
r := strings.NewReplacer(
"{{apikey}}", dc.apiKEY,
"{{chatid}}", dc.chatID,
"{{message}}", message,
)
URL := r.Replace(Endpoint)
req, err := retryablehttp.NewRequest(http.MethodGet, URL, nil)
if err != nil {
return err
}
resp, err := dc.client.Do(req)
if err != nil {
return err
}
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
//nolint:errcheck // silent fail
defer resp.Body.Close()
var tgresponse TelegramResponse
err = json.Unmarshal(buf, &tgresponse)
if err != nil {
return err
}
if !tgresponse.Ok {
return fmt.Errorf("%s", tgresponse.Description)
}
return nil
}
// TelegramResponse structure
type TelegramResponse struct {
Ok bool `json:"ok"`
ErrorCode int `json:"error_code,omitempty"`
Description string `json:"description,omitempty"`
}