-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
359 lines (315 loc) · 10.2 KB
/
main.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package main
import (
"flag"
"fmt"
"os"
"regexp"
"sort"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/nlopes/slack"
"github.com/sirupsen/logrus"
)
const extractMsgGroupName = "msg"
// extract suffixes of Slack messages starting with @bot-name
var extractMsgPattern = `(?m)^\s*<@%s>:?\s*(?P<` + extractMsgGroupName + `>.*)$`
// A standupMsg is a Slack message directed to the arriba bot (i.e. with a @botname prefix)
type standupMsg struct {
ts time.Time
text string
}
// channelStandup contains the latest standup message of each user in a Slack channel.
type channelStandup map[string]standupMsg
// sortableChannelStandup is a channelStandup, sortable by the timestamp of its messages
// sortableChannelStandup implements sort.Interface to sort the keys of the channelStandup
type sortableChannelStandup struct {
keys []string
cs channelStandup
}
func (s sortableChannelStandup) Swap(i, j int) { s.keys[i], s.keys[j] = s.keys[j], s.keys[i] }
func (s sortableChannelStandup) Len() int { return len(s.keys) }
func (s sortableChannelStandup) Less(i, j int) bool {
return s.cs[s.keys[i]].ts.After(s.cs[s.keys[j]].ts)
}
// getKeysByTimestamp returns the userIDs of the standup ordered by their message timestamp (newer first).
func (cs channelStandup) getKeysByTimestamp() []string {
keys := make([]string, 0, len(cs))
for k := range cs {
keys = append(keys, k)
}
scs := sortableChannelStandup{
cs: cs,
keys: keys,
}
sort.Sort(scs)
return scs.keys
}
// standups contains the channelStandup of all Slack channels known to the bot.
type standups map[string]channelStandup
// conversation is a generic way to access the IDs, Names and history of both
// slack.Channel and slack.Group. Unfortunately nlopes/slack doesn't expose the
// underlying common type (groupConversation) and we cannot define methods for
// non-local types, which would allow to make things much cleaner ...
type conversation interface {
getID() string
getName() string
getHistory(*slack.RTM, slack.HistoryParameters) (*slack.History, error)
}
type channel slack.Channel
func (c channel) getID() string { return c.ID }
func (c channel) getName() string { return c.Name }
func (c channel) getHistory(rtm *slack.RTM, params slack.HistoryParameters) (*slack.History, error) {
return rtm.GetChannelHistory(c.getID(), params)
}
type group slack.Group
func (g group) getID() string { return g.ID }
func (g group) getName() string { return g.Name }
func (g group) getHistory(rtm *slack.RTM, params slack.HistoryParameters) (*slack.History, error) {
return rtm.GetGroupHistory(g.getID(), params)
}
type arriba struct {
rtm *slack.RTM
botID string
botName string
extractMsgRE *regexp.Regexp
historyDaysLimit int
standups standups
}
func newArriba(rtm *slack.RTM, historyDaysLimit int) arriba {
return arriba{
rtm: rtm,
historyDaysLimit: historyDaysLimit,
standups: make(standups),
}
}
func parseSlackTimeStamp(ts string) (time.Time, error) {
var seconds, milliseconds int64
_, err := fmt.Sscanf(ts, "%d.%d", &seconds, &milliseconds)
if err != nil {
logrus.Warn("Can't parse timestamp ", ts)
return time.Now(), err
}
return time.Unix(seconds, milliseconds*1000), nil
}
// extractStandupMsg parses Slack messages starting with @bot-name
func (a arriba) extractChannelStandupMsg(msg slack.Msg) (standupMsg, bool) {
if msg.Type != "message" || msg.SubType != "" {
return standupMsg{}, false
}
standupText := a.extractMsgRE.ReplaceAllString(msg.Text, "$"+extractMsgGroupName)
if len(standupText) == len(msg.Text) {
// Nothing was extracted
return standupMsg{}, false
}
ts, err := parseSlackTimeStamp(msg.Timestamp)
if err != nil {
return standupMsg{}, false
}
return standupMsg{ts, standupText}, true
}
func (a arriba) retrieveChannelStandup(c conversation) (channelStandup, error) {
params := slack.NewHistoryParameters()
params.Count = 1000
now := time.Now().UTC()
params.Latest = fmt.Sprintf("%d", now.Unix())
params.Oldest = fmt.Sprintf("%d", now.AddDate(0, 0, -a.historyDaysLimit).Unix())
// It would be way more efficient to use slack.SearchMsgs instead
// of traversing the whole history, but that's not allowed for bots :(
cstandup := make(channelStandup)
for {
logrus.Debugf(
"Requesting history for conversation %s with parameters %#v",
c.getID(),
params)
history, error := c.getHistory(a.rtm, params)
if error != nil || history == nil || len(history.Messages) == 0 {
return cstandup, error
}
logrus.Debugf(
"Got history chunk (from %s to %s, latest %s) for conversation %s",
history.Messages[len(history.Messages)-1].Msg.Timestamp,
history.Messages[0].Msg.Timestamp, history.Latest, c.getID())
for _, msg := range history.Messages {
if _, ok := cstandup[msg.User]; ok {
// we already have the latest standup message for this user
continue
}
standupMsg, ok := a.extractChannelStandupMsg(msg.Msg)
if ok && standupMsg.text != "" {
cstandup[msg.User] = standupMsg
}
}
if !history.HasMore {
break
}
latestMsg := history.Messages[len(history.Messages)-1]
params.Latest = latestMsg.Timestamp
params.Inclusive = false
}
return cstandup, nil
}
func (a arriba) retrieveStandups(conversations []conversation) {
for _, c := range conversations {
logrus.Infof("Retrieveing standup for conversation #%s (%s)", c.getName(), c.getID())
cstandup, err := a.retrieveChannelStandup(c)
if err != nil {
logrus.Errorf("Can't retrieve channel standup for conversation #%s: %s", c.getName(), err)
}
a.standups[c.getID()] = cstandup
logrus.Infof("Standup for conversation #%s (%s) updated to %#v", c.getName(), c.getID(), cstandup)
}
}
func (a arriba) getUserName(userID string) string {
info, err := a.rtm.GetUserInfo(userID)
userName := "id" + userID
if err != nil {
logrus.Errorf("Couldn't get user information for user %s: %s", userID, err)
} else {
userName = info.Name
}
return userName
}
func (a arriba) removeOldMessages(channelID string) {
cstandup, ok := a.standups[channelID]
if !ok {
return
}
oldestAllowed := time.Now().UTC().AddDate(0, 0, -a.historyDaysLimit)
for userID, msg := range cstandup {
if msg.ts.Before(oldestAllowed) {
delete(cstandup, userID)
}
}
}
func (a arriba) prettyPrintChannelStandup(cstandup channelStandup) string {
text := "¡Ándale! ¡Ándale! here's the standup status :tada:\n"
for _, userID := range cstandup.getKeysByTimestamp() {
standupMsg := cstandup[userID]
humanTime := humanize.Time(standupMsg.ts)
userName := a.getUserName(userID)
// Inject zero-width unicode character in username to avoid notifying users
if len(userName) > 1 {
userName = string(userName[0]) + "\ufeff" + string(userName[1:])
}
text += fmt.Sprintf("*%s*: %s _(%s)_\n", userName, standupMsg.text, humanTime)
}
return text
}
func (a arriba) sendStatus(channelID string) {
var statusText string
if cstandup, ok := a.standups[channelID]; ok && len(cstandup) > 0 {
statusText = a.prettyPrintChannelStandup(cstandup)
} else {
statusText = fmt.Sprintf("No standup messages found\nType a message starting with *@%s* to record your standup message", a.botName)
}
a.rtm.SendMessage(a.rtm.NewOutgoingMessage(statusText, channelID))
}
func (a arriba) updateLastStandup(channelID, userID string, msg standupMsg) {
if _, ok := a.standups[channelID]; !ok {
a.standups[channelID] = make(channelStandup)
}
a.standups[channelID][userID] = msg
confirmationText := fmt.Sprintf("<@%s>: ¡Yeppa! standup status recorded :taco:", userID)
a.rtm.SendMessage(a.rtm.NewOutgoingMessage(confirmationText, channelID))
}
func (a *arriba) handleConnectedEvent(ev *slack.ConnectedEvent) {
if a.botID != "" {
logrus.Warn("Received unexpected Connected event")
return
}
logrus.Infof(
"Connected as user %s (%s) to team %s (%s)",
ev.Info.User.Name,
ev.Info.User.ID,
ev.Info.Team.Name,
ev.Info.Team.ID,
)
a.botID = ev.Info.User.ID
a.botName = ev.Info.User.Name
a.extractMsgRE = regexp.MustCompile(fmt.Sprintf(extractMsgPattern, a.botID))
// Retrieve standups for public channels and private groups
var conversations []conversation
for _, c := range ev.Info.Channels {
if c.IsMember {
conversations = append(conversations, channel(c))
}
}
for _, g := range ev.Info.Groups {
conversations = append(conversations, group(g))
}
a.retrieveStandups(conversations)
}
func (a arriba) handleMessageEvent(ev *slack.MessageEvent) {
logrus.Debugf("Message received %+v", ev)
if a.botID == "" {
logrus.Warn("Received message event before finishing initialization")
return
}
if ev.Channel == "" {
logrus.Warn("Received message with empty channel")
return
}
switch ev.Channel[0] {
case 'C', 'G':
// Public and private (group) channels
smsg, ok := a.extractChannelStandupMsg(ev.Msg)
if !ok {
return
}
logrus.Infof("Received standup message in channel %s: %+v", ev.Channel, smsg)
// Garbage-collect old messages
a.removeOldMessages(ev.Msg.Channel)
if smsg.text == "" {
a.sendStatus(ev.Msg.Channel)
} else {
a.updateLastStandup(ev.Msg.Channel, ev.Msg.User, smsg)
}
case 'D':
// Direct messages are not supported yet
}
}
func (a arriba) run() {
go a.rtm.ManageConnection()
for {
select {
case msg := <-a.rtm.IncomingEvents:
switch ev := msg.Data.(type) {
case *slack.ConnectedEvent:
a.handleConnectedEvent(ev)
case *slack.MessageEvent:
a.handleMessageEvent(ev)
case *slack.RTMError:
logrus.Error("Invalid credentials", ev.Error())
case *slack.InvalidAuthEvent:
logrus.Error("Invalid credentials")
os.Exit(1)
}
}
}
}
func usage() {
fmt.Fprintf(os.Stderr, "usage: %s [ flags ] <SlackAPItoken>\n", os.Args[0])
flag.PrintDefaults()
fmt.Fprintf(os.Stderr, "You can obtain <SlackAPItoken> from https://<yourteam>.slack.com/services/new/bot\n")
}
func main() {
var (
debug bool
historyDaysLimit int
)
flag.Usage = usage
flag.BoolVar(&debug, "debug", false, "Print debug information")
flag.IntVar(&historyDaysLimit, "history-limit", 7, "History limit (in days)")
flag.Parse()
if len(flag.Args()) < 1 || historyDaysLimit < 1 {
usage()
os.Exit(1)
}
logrus.SetOutput(os.Stderr)
if debug {
logrus.SetLevel(logrus.DebugLevel)
}
api := slack.New(flag.Arg(0))
api.SetDebug(debug)
newArriba(api.NewRTM(), historyDaysLimit).run()
}