Passed
Pull Request — master (#762)
by
unknown
06:31
created

report.sendMessage   A

Complexity

Conditions 3

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 16
dl 0
loc 25
c 0
b 0
f 0
rs 9.6
nop 3
1
package report
2
3
import (
4
	"bytes"
5
	"fmt"
6
	"net/http"
7
	"strconv"
8
	"strings"
9
10
	"github.com/future-architect/vuls/config"
11
	"github.com/future-architect/vuls/models"
12
)
13
14
// ChatWorkWriter send report to ChatWork
0 ignored issues
show
introduced by
comment on exported type TelegramWriter should be of the form "TelegramWriter ..." (with optional leading article)
Loading history...
15
type TelegramWriter struct{}
16
17
func (w TelegramWriter) Write(rs ...models.ScanResult) (err error) {
18
	conf := config.Conf.Telegram
19
20
	for _, r := range rs {
21
		serverInfo := fmt.Sprintf("%s", r.ServerInfo())
22
		for _, vinfo := range r.ScannedCves {
23
			maxCvss := vinfo.MaxCvssScore()
24
			severity := strings.ToUpper(maxCvss.Value.Severity)
25
			if severity == "" {
26
				severity = "?"
27
			}
28
29
			message := fmt.Sprintf(`*%s*
30
[%s](https://nvd.nist.gov/vuln/detail/%s) _%s %s_
31
%s`,
32
				serverInfo,
33
				vinfo.CveID,
34
				vinfo.CveID,
35
				strconv.FormatFloat(maxCvss.Value.Score, 'f', 1, 64),
36
				severity,
37
				vinfo.Summaries(config.Conf.Lang, r.Family)[0].Value)
38
39
			if err = sendMessage(conf.Channel, conf.Token, message); err != nil {
40
				return err
41
			}
42
		}
43
44
	}
45
	return nil
46
}
47
48
func sendMessage(channel, token, message string) error {
49
	fmt.Println(message)
50
51
	uri := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", token)
52
53
	payload := `{"text": "` + message + `", "chat_id": "@` + channel + `", "parse_mode": "Markdown" }`
54
55
	req, err := http.NewRequest("POST", uri, bytes.NewBuffer([]byte(payload)))
56
57
	req.Header.Add("Content-Type", "application/json")
58
59
	if err != nil {
60
		return err
61
	}
62
	client := &http.Client{}
63
64
	resp, err := client.Do(req)
65
	if err != nil {
66
		fmt.Println(err)
67
		return err
68
	}
69
	fmt.Println("###########################")
70
	defer resp.Body.Close()
71
72
	return nil
73
}
74