forked from viliproject/vili
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slack.go
250 lines (220 loc) · 5.21 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
package slack
import (
"fmt"
"regexp"
"strings"
"sync"
"time"
"github.com/airware/vili/log"
"github.com/airware/vili/util"
"github.com/nlopes/slack"
)
// WaitGroup is the wait group to synchronize slack rtm shutdowns
var WaitGroup sync.WaitGroup
// Exiting is a flag indicating that the server is exiting
var Exiting = false
var config *Config
var client *slack.Client
var slackLinkRegexp = regexp.MustCompile(`<.+?\|.+?>`)
// Config is the slack configuration
type Config struct {
Token string
Channel string
Username string
Emoji string
DeployUsernames *util.StringSet
}
// Init initializes the slack client
func Init(c *Config) error {
config = c
client = slack.New(c.Token)
return nil
}
// PostLogMessage posts a formatted log message to slack
func PostLogMessage(message, level string) error {
if client == nil {
return nil
}
color := "#36a64f"
switch level {
case "error":
color = "#ff3300"
case "warn":
color = "#ffaa00"
}
_, _, err := client.PostMessage(config.Channel, "", slack.PostMessageParameters{
Username: config.Username,
IconEmoji: config.Emoji,
Attachments: []slack.Attachment{
slack.Attachment{
Color: color,
Text: message,
MarkdownIn: []string{"text"},
},
},
})
return err
}
// MentionsRegexp returns a regexp matching messages which mention the configured user
func MentionsRegexp() (*regexp.Regexp, error) {
var botID string
users, err := client.GetUsers()
if err != nil {
return nil, err
}
for _, user := range users {
if user.Name == config.Username {
botID = user.ID
break
}
}
if botID == "" {
return nil, fmt.Errorf("User %s not found", config.Username)
}
return regexp.Compile(fmt.Sprintf("^<@(?:%s|%s)>: (.*)", botID, config.Username))
}
// ListenForMessages opens an RTM connection to slack and listens for any messages
// in the configured channel which matches any of the regexps and sends the message
// to the mapped channel
func ListenForMessages(messageMap map[*regexp.Regexp]chan<- *Message) {
var waitGroup sync.WaitGroup
var channelID string
deployUsers := map[string]string{}
failed := false
channelName := strings.TrimLeft(config.Channel, "#")
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
// get a list of user ids with deploy permissions
users, err := client.GetUsers()
if err != nil {
log.Error(err)
failed = true
return
}
for _, user := range users {
if config.DeployUsernames.Contains(user.Name) {
deployUsers[user.ID] = user.Name
}
}
}()
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
// look for the channel id
channels, err := client.GetChannels(true)
if err != nil {
log.Error(err)
failed = true
return
}
for _, channel := range channels {
if channel.Name == channelName {
channelID = channel.ID
break
}
}
}()
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
// look for the channel id
groups, err := client.GetGroups(true)
if err != nil {
log.Error(err)
failed = true
return
}
for _, group := range groups {
if group.Name == channelName {
channelID = group.ID
break
}
}
}()
waitGroup.Wait()
if failed {
return
}
if channelID == "" {
log.Errorf("Channel %s not found", config.Channel)
return
}
rtm := client.NewRTM()
go rtm.ManageConnection()
WaitGroup.Add(1)
go func() {
IncomingEvents:
for event := range rtm.IncomingEvents {
switch ev := event.Data.(type) {
case *slack.MessageEvent:
username, ok := deployUsers[ev.User]
if !ok {
continue
}
if ev.Channel == channelID {
log.Debug(ev.User)
log.Debug(ev.Text)
for re, ch := range messageMap {
if match := re.FindStringSubmatch(ev.Text); len(match) > 0 {
ch <- &Message{
Timestamp: ev.Timestamp,
Text: match[0],
Matches: match[1:],
Username: username,
}
} else {
if match := re.FindStringSubmatch(removeLinks(ev.Text)); len(match) > 0 {
ch <- &Message{
Timestamp: ev.Timestamp,
Text: match[0],
Matches: match[1:],
Username: username,
}
}
}
}
}
case *slack.RTMError:
log.Error(ev.Error())
case *slack.ConnectedEvent:
log.Infof("RTM Connected, Connection count: %d", ev.ConnectionCount)
case *slack.DisconnectedEvent:
log.Infof("RTM disconnected, Intentional: %v", ev.Intentional)
if ev.Intentional {
break IncomingEvents
}
default:
// ignore other events
}
}
WaitGroup.Done()
}()
log.Info("Started slack rtm")
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for !Exiting {
<-ticker.C
}
log.Info("Disconnecting slack rtm")
err := rtm.Disconnect()
if err != nil {
log.Error(err)
}
for _, ch := range messageMap {
close(ch)
}
}
func removeLinks(message string) string {
return slackLinkRegexp.ReplaceAllStringFunc(message, func(match string) string {
sepIndex := strings.LastIndex(match, "|")
return match[sepIndex+1 : len(match)-1]
})
}
// Message is a slack message from the configured channel
type Message struct {
Timestamp string // this is guaranteed to be unique per channel
Text string
Matches []string
Username string
}