-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessenger.go
115 lines (93 loc) · 2.52 KB
/
messenger.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package manago
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
)
type Messenger interface {
Send(Message) error
QuickSend(string) error
}
type Slack struct {
HookUrl string
}
type Message struct {
Topic string
Body string
LinkUrl *string
LinkText *string
}
func (ms *Message) GetSlackMessage() ([]byte, error) {
type SlackText struct {
Type string `json:"type,omitempty"`
Text string `json:"text"`
Emoji bool `json:"emoji,omitempty"`
}
type SlackAccessory struct {
Type string `json:"type,omitempty"`
Text *SlackText `json:"text,omitempty"`
Value string `json:"value,omitempty"`
Url string `json:"url,omitempty"`
ActionId string `json:"action_id,omitempty"`
}
type SlackBlock struct {
Type string `json:"type"`
Text *SlackText `json:"text,omitempty"`
Accessory *SlackAccessory `json:"accessory,omitempty"`
}
type SlackMessage struct {
Blocks []SlackBlock `json:"blocks,omitempty"`
}
msg := SlackMessage{}
msg.Blocks = []SlackBlock{
SlackBlock{Type: "divider"},
}
if len(ms.Topic) > 0 {
topicBlock := &SlackText{Type: "plain_text", Text: ms.Topic, Emoji: true}
msg.Blocks = append(msg.Blocks, SlackBlock{Type: "header", Text: topicBlock})
}
if len(ms.Body) > 0 {
bodyBlock := &SlackText{Type: "plain_text", Text: ms.Body, Emoji: true}
msg.Blocks = append(msg.Blocks, SlackBlock{Type: "section", Text: bodyBlock})
}
return json.Marshal(msg)
}
func (sl *Slack) Send(msg Message) error {
reqUrl, err := url.Parse(sl.HookUrl)
if err != nil {
return fmt.Errorf("Parsing Api Url failed: %v", err)
}
jsonMsg, err := msg.GetSlackMessage()
if err != nil {
return fmt.Errorf("Parsing message to json failed: %v\n", err)
}
request, err := http.NewRequest("POST", reqUrl.String(), bytes.NewBuffer(jsonMsg))
if err != nil {
return fmt.Errorf("Preparing request failed: %v", err)
}
request.Header.Set("Content-Type", "application/json")
client := &http.Client{
Timeout: time.Second * 3,
}
resp, err := client.Do(request)
if err != nil {
return fmt.Errorf("Failed doing request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return fmt.Errorf("Received non success response: %s", resp.Status)
}
// decode := json.NewDecoder(resp.Body)
// err = decode.Decode(em.LastState)
// if err != nil {
// return fmt.Errorf("Decoding json failed: %v", err)
// }
return nil
}
func (sl *Slack) QuickSend(text string) error {
message := Message{Body: text}
return sl.Send(message)
}