-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.go
97 lines (82 loc) · 2.02 KB
/
bot.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 groupme
import (
"bytes"
"encoding/json"
"net/http"
"strings"
)
// Bot is a GroupMe Bot.
type Bot struct {
BaseURL string
ID string
GroupID string
GroupName string
AvatarURL string
}
// BotPost is a message from a Bot.
type BotPost struct {
BotID string `json:"bot_id"`
Text string `json:"text"`
Attachments []Attachment `json:"attachments"`
}
// NewBot returns a new GroupMe Bot.
func NewBot(baseURL, ID, groupID, groupName, avatarURL string) Bot {
return Bot{
BaseURL: baseURL,
ID: ID,
GroupID: groupID,
GroupName: groupName,
AvatarURL: avatarURL,
}
}
// Post posts a message.
func (b *Bot) Post(message string, attachments []Attachment) error {
// generate URL for request
URL, err := createURL(b.BaseURL, "/bots/post", "")
if err != nil {
return err
}
// chunk message down to lengths of 1000 or less
for _, buf := range b.getBufferedMessage(message, "\n") {
post := BotPost{
BotID: b.ID,
Text: buf,
Attachments: attachments,
}
jsonStr, err := json.Marshal(post)
if err != nil {
return err
}
req, err := http.NewRequest("POST", URL, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusAccepted {
return parseError(resp.StatusCode, resp.Status)
}
}
return nil
}
// getBufferedMessage returns a list of strings no bigger than
// what is allowed to be sent as a GroupMe Bot message (length: 1000).
func (b *Bot) getBufferedMessage(s, sep string) []string {
list := []string{}
var strBuilder string
split := strings.Split(s, sep)
for _, part := range split {
if len(strBuilder)+len(part)+len(sep) <= 1000 {
strBuilder += part + sep
} else {
list = append(list, strings.TrimSpace(strBuilder))
strBuilder = part + sep
}
}
if len(strBuilder) > 0 {
list = append(list, strings.TrimSpace(strBuilder))
}
return list
}