forked from saurabh-agarwals/slack
/
chat.go
97 lines (90 loc) · 2.2 KB
/
chat.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
package slack
import (
"bytes"
"encoding/json"
"errors"
"net/url"
)
// API chat.postMessage: Sends a message to a channel.
func (sl *Slack) ChatPostMessage(channelId string, threadTs string, broadcast string, text string, opt *ChatPostMessageOpt) (*ChatPostMessageAPIResponse, error) {
uv, err := sl.buildChatPostMessageUrlValues(opt)
if err != nil {
return nil, err
}
uv.Add("channel", channelId)
if threadTs != "" {
uv.Add("thread_ts", threadTs)
uv.Add("reply_broadcast", broadcast)
}
body, err := sl.PostRequest(chatPostMessageApiEndpoint, uv, sl.buildRequestBodyForm(text))
if err != nil {
return nil, err
}
res := new(ChatPostMessageAPIResponse)
err = json.Unmarshal(body, res)
if err != nil {
return res, err
}
if !res.Ok {
return res, errors.New(res.Error)
}
return res, nil
}
// option type for `chat.postMessage` api
type ChatPostMessageOpt struct {
AsUser bool
Username string
Parse string
LinkNames string
Attachments []*Attachment
UnfurlLinks string
UnfurlMedia string
IconUrl string
IconEmoji string
}
// response type for `chat.postMessage` api
type ChatPostMessageAPIResponse struct {
BaseAPIResponse
Channel string `json:"channel"`
Ts string `json:"ts"`
}
func (sl *Slack) buildRequestBodyForm(text string) *bytes.Buffer {
return bytes.NewBuffer([]byte("text=" + url.QueryEscape(text)))
}
func (sl *Slack) buildChatPostMessageUrlValues(opt *ChatPostMessageOpt) (*url.Values, error) {
uv := sl.urlValues()
if opt == nil {
return uv, nil
}
if opt.AsUser {
uv.Add("as_user", "true")
} else if opt.Username != "" {
uv.Add("username", opt.Username)
}
if opt.Parse != "" {
uv.Add("parse", opt.Parse)
}
if opt.LinkNames != "" {
uv.Add("link_names", opt.LinkNames)
}
if opt.UnfurlLinks != "" {
uv.Add("unfurl_links", opt.UnfurlLinks)
}
if opt.UnfurlMedia != "" {
uv.Add("unfurl_media", opt.UnfurlMedia)
}
if opt.IconUrl != "" {
uv.Add("icon_url", opt.IconUrl)
}
if opt.IconEmoji != "" {
uv.Add("icon_emoji", opt.IconEmoji)
}
if opt.Attachments != nil && len(opt.Attachments) > 0 {
ats, err := json.Marshal(opt.Attachments)
if err != nil {
return nil, err
}
uv.Add("attachments", string(ats))
}
return uv, nil
}