-
Notifications
You must be signed in to change notification settings - Fork 1
/
slack.go
94 lines (78 loc) · 1.86 KB
/
slack.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
package narada
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
type (
SlackClient struct {
Url string
c *http.Client
}
SlackMessage struct {
Text string `json:"text"`
Username string `json:"username"`
IconUrl string `json:"icon_url"`
IconEmoji string `json:"icon_emoji"`
Channel string `json:"channel"`
UnfurlLinks bool `json:"unfurl_links"`
Attachments []*SlackAttachment `json:"attachments"`
}
SlackAttachment struct {
Title string `json:"title"`
Fallback string `json:"fallback"`
Text string `json:"text"`
Pretext string `json:"pretext"`
Color string `json:"color"`
Fields []*SlackField `json:"fields"`
}
SlackField struct {
Title string `json:"title"`
Value string `json:"value"`
Short bool `json:"short"`
}
SlackError struct {
Code int
Body string
}
)
func (e *SlackError) Error() string {
return fmt.Sprintf("SlackError: %d %s", e.Code, e.Body)
}
func NewClient(url string) *SlackClient {
return &SlackClient{
Url: url,
c: &http.Client{
Timeout: time.Second * 10,
},
}
}
func (c *SlackClient) SendMessage(msg *SlackMessage) error {
body, _ := json.Marshal(msg)
buf := bytes.NewReader(body)
resp, err := c.c.Post(c.Url, "application/json", buf)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t, _ := ioutil.ReadAll(resp.Body)
return &SlackError{resp.StatusCode, string(t)}
}
return nil
}
func NewAttachment() *SlackAttachment {
return &SlackAttachment{}
}
func (m *SlackMessage) AddAttachment(a *SlackAttachment) {
m.Attachments = append(m.Attachments, a)
}
func NewField() *SlackField {
return &SlackField{}
}
func (a *SlackAttachment) AddField(f *SlackField) {
a.Fields = append(a.Fields, f)
}