forked from shomali11/slacker
-
Notifications
You must be signed in to change notification settings - Fork 1
/
slacker.go
524 lines (449 loc) · 16.1 KB
/
slacker.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
package slacker
import (
"context"
"errors"
"fmt"
"log"
"strings"
"github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
"github.com/slack-go/slack/socketmode"
allot "github.com/sdslabs/allot/pkg"
)
const (
space = " "
dash = "-"
star = "*"
newLine = "\n"
invalidToken = "invalid token"
helpCommand = "(Bot|bot) help"
directChannelMarker = "D"
userMentionFormat = "<@%s>"
codeMessageFormat = "`%s`"
boldMessageFormat = "*%s*"
italicMessageFormat = "_%s_"
quoteMessageFormat = ">_*Example:* %s_"
authorizedUsersOnly = "Authorized users only"
slackBotUser = "USLACKBOT"
botPrefix = "(Bot|bot) "
)
var (
defaultIncludeChannelIds = []string{"all"}
errUnauthorized = errors.New("you are not authorized to execute this command")
)
func defaultCleanEventInput(msg string) string {
return strings.ReplaceAll(msg, "\u00a0", " ")
}
// NewClient creates a new client using the Slack API
func NewClient(botToken, appToken string, options ...ClientOption) *Slacker {
defaults := newClientDefaults(options...)
api := slack.New(
botToken,
slack.OptionDebug(defaults.Debug),
slack.OptionAppLevelToken(appToken),
)
smc := socketmode.New(
api,
socketmode.OptionDebug(defaults.Debug),
)
slacker := &Slacker{
client: api,
socketModeClient: smc,
commandChannel: make(chan *CommandEvent, 100),
errUnauthorized: errUnauthorized,
botInteractionMode: defaults.BotMode,
cleanEventInput: defaultCleanEventInput,
}
return slacker
}
// Slacker contains the Slack API, botCommands, and handlers
type Slacker struct {
client *slack.Client
socketModeClient *socketmode.Client
botCommands []BotCommand
botContextConstructor func(ctx context.Context, api *slack.Client, client *socketmode.Client, evt *MessageEvent) BotContext
commandConstructor func(usage string, definition *CommandDefinition) BotCommand
requestConstructor func(botCtx BotContext, params []allot.Parameter, match allot.MatchInterface) Request
responseConstructor func(botCtx BotContext) ResponseWriter
initHandler func()
errorHandler func(err string)
interactiveEventHandler func(*Slacker, *socketmode.Event, *slack.InteractionCallback)
helpDefinition *CommandDefinition
defaultMessageHandler func(botCtx BotContext, request Request, response ResponseWriter)
defaultEventHandler func(interface{})
errUnauthorized error
commandChannel chan *CommandEvent
appID string
botInteractionMode BotInteractionMode
cleanEventInput func(in string) string
}
// BotCommands returns Bot Commands
func (s *Slacker) BotCommands() []BotCommand {
return s.botCommands
}
// Client returns the internal slack.Client of Slacker struct
func (s *Slacker) Client() *slack.Client {
return s.client
}
// SocketMode returns the internal socketmode.Client of Slacker struct
func (s *Slacker) SocketMode() *socketmode.Client {
return s.socketModeClient
}
// Init handle the event when the bot is first connected
func (s *Slacker) Init(initHandler func()) {
s.initHandler = initHandler
}
// Err handle when errors are encountered
func (s *Slacker) Err(errorHandler func(err string)) {
s.errorHandler = errorHandler
}
// CleanEventInput allows the api consumer to override the default event input cleaning behavior
func (s *Slacker) CleanEventInput(cei func(in string) string) {
s.cleanEventInput = cei
}
// Interactive assigns an interactive event handler
func (s *Slacker) Interactive(interactiveEventHandler func(*Slacker, *socketmode.Event, *slack.InteractionCallback)) {
s.interactiveEventHandler = interactiveEventHandler
}
// CustomBotContext creates a new bot context
func (s *Slacker) CustomBotContext(botContextConstructor func(ctx context.Context, api *slack.Client, client *socketmode.Client, evt *MessageEvent) BotContext) {
s.botContextConstructor = botContextConstructor
}
// CustomCommand creates a new BotCommand
func (s *Slacker) CustomCommand(commandConstructor func(usage string, definition *CommandDefinition) BotCommand) {
s.commandConstructor = commandConstructor
}
// CustomRequest creates a new request
func (s *Slacker) CustomRequest(requestConstructor func(botCtx BotContext, parameters []allot.Parameter,
match allot.MatchInterface) Request) {
s.requestConstructor = requestConstructor
}
// CustomResponse creates a new response writer
func (s *Slacker) CustomResponse(responseConstructor func(botCtx BotContext) ResponseWriter) {
s.responseConstructor = responseConstructor
}
// DefaultCommand handle messages when none of the commands are matched
func (s *Slacker) DefaultCommand(defaultMessageHandler func(botCtx BotContext, request Request, response ResponseWriter)) {
s.defaultMessageHandler = defaultMessageHandler
}
// DefaultEvent handle events when an unknown event is seen
func (s *Slacker) DefaultEvent(defaultEventHandler func(interface{})) {
s.defaultEventHandler = defaultEventHandler
}
// UnAuthorizedError error message
func (s *Slacker) UnAuthorizedError(errUnauthorized error) {
s.errUnauthorized = errUnauthorized
}
// Help handle the help message, it will use the default if not set
func (s *Slacker) Help(definition *CommandDefinition) {
s.helpDefinition = definition
}
// Command define a new command and append it to the list of existing commands
func (s *Slacker) Command(usage string, definition *CommandDefinition) {
s.botCommands = append(s.botCommands, NewBotCommand(usage, definition, true, defaultIncludeChannelIds))
}
// BotCommand define a new bot command and append it to the list of existing commands
func (s *Slacker) BotCommand(usage string, definition *CommandDefinition) {
s.botCommands = append(s.botCommands, NewBotCommand(botPrefix+usage, definition, true, defaultIncludeChannelIds))
}
// GeneralCommand define a new bot non parameterized command and append it to the list of existing commands
func (s *Slacker) GeneralCommand(usage string, definition *CommandDefinition) {
s.botCommands = append(s.botCommands, NewBotCommand(usage, definition, false, defaultIncludeChannelIds))
}
// CommandWithIncludeChannels define a new command and append it to the list of existing commands with include channels filter
func (s *Slacker) CommandWithIncludeChannels(usage string, definition *CommandDefinition, includeChannelIds []string) {
s.botCommands = append(s.botCommands, NewBotCommand(usage, definition, true, includeChannelIds))
}
// BotCommandWithIncludeChannels define a new bot command and append it to the list of existing commands with include channels filter
func (s *Slacker) BotCommandWithIncludeChannels(usage string, definition *CommandDefinition, includeChannelIds []string) {
s.botCommands = append(s.botCommands, NewBotCommand(botPrefix+usage, definition, true, includeChannelIds))
}
/*
GeneralCommandWithIncludeChannels define a new bot non parameterized command and
append it to the list of existing commands with include channels filter
*/
func (s *Slacker) GeneralCommandWithIncludeChannels(usage string, definition *CommandDefinition, includeChannelIds []string) {
s.botCommands = append(s.botCommands, NewBotCommand(usage, definition, false, includeChannelIds))
}
// CommandEvents returns read only command events channel
func (s *Slacker) CommandEvents() <-chan *CommandEvent {
return s.commandChannel
}
// Listen receives events from Slack and each is handled as needed
func (s *Slacker) Listen(ctx context.Context) error {
s.prependHelpHandle()
go func() {
for {
select {
case <-ctx.Done():
return
case evt, ok := <-s.socketModeClient.Events:
if !ok {
return
}
switch evt.Type {
case socketmode.EventTypeConnecting:
fmt.Println("Connecting to Slack with Socket Mode.")
if s.initHandler == nil {
continue
}
go s.initHandler()
case socketmode.EventTypeConnectionError:
fmt.Println("Connection failed. Retrying later...")
case socketmode.EventTypeConnected:
fmt.Println("Connected to Slack with Socket Mode.")
case socketmode.EventTypeHello:
s.appID = evt.Request.ConnectionInfo.AppID
fmt.Printf("Connected as App ID %v\n", s.appID)
case socketmode.EventTypeEventsAPI:
ev, ok := evt.Data.(slackevents.EventsAPIEvent)
if !ok {
fmt.Printf("Ignored %+v\n", evt)
continue
}
switch ev.InnerEvent.Type {
case "message", "app_mention": // message-based events
go s.handleMessageEvent(ctx, ev.InnerEvent.Data, nil)
default:
fmt.Printf("unsupported inner event: %+v\n", ev.InnerEvent.Type)
}
s.socketModeClient.Ack(*evt.Request)
case socketmode.EventTypeSlashCommand:
callback, ok := evt.Data.(slack.SlashCommand)
if !ok {
fmt.Printf("Ignored %+v\n", evt)
continue
}
s.socketModeClient.Ack(*evt.Request)
go s.handleMessageEvent(ctx, &callback, evt.Request)
case socketmode.EventTypeInteractive:
callback, ok := evt.Data.(slack.InteractionCallback)
if !ok {
fmt.Printf("Ignored %+v\n", evt)
continue
}
go s.handleInteractiveEvent(s, &evt, &callback, evt.Request)
default:
if s.defaultEventHandler != nil {
s.defaultEventHandler(evt)
} else {
s.unsupportedEventReceived()
}
}
}
}
}()
// blocking call that handles listening for events and placing them in the
// Events channel as well as handling outgoing events.
return s.socketModeClient.RunContext(ctx)
}
func (s *Slacker) unsupportedEventReceived() {
s.socketModeClient.Debugf("unsupported Events API event received")
}
// GetUserInfo retrieve complete user information
func (s *Slacker) GetUserInfo(user string) (*slack.User, error) {
return s.client.GetUserInfo(user)
}
func (s *Slacker) defaultHelp(botCtx BotContext, request Request, response ResponseWriter) {
authorizedCommandAvailable := false
helpMessage := empty
for _, command := range s.botCommands {
if command.Definition().HideHelp {
continue
}
tokens := command.Tokenize()
for _, token := range tokens {
if token.IsParameter() {
helpMessage += fmt.Sprintf(codeMessageFormat, token.Word()) + space
} else {
helpMessage += fmt.Sprintf(boldMessageFormat, token.Word()) + space
}
}
if len(command.Definition().Description) > 0 {
helpMessage += dash + space + fmt.Sprintf(italicMessageFormat, command.Definition().Description)
}
if command.Definition().AuthorizationFunc != nil {
authorizedCommandAvailable = true
helpMessage += space + fmt.Sprintf(codeMessageFormat, star)
}
helpMessage += newLine
for _, example := range command.Definition().Examples {
helpMessage += fmt.Sprintf(quoteMessageFormat, example) + newLine
}
}
if authorizedCommandAvailable {
helpMessage += fmt.Sprintf(codeMessageFormat, star+space+authorizedUsersOnly) + newLine
}
err := response.Reply(helpMessage)
if err != nil {
log.Println(err)
}
}
func (s *Slacker) prependHelpHandle() {
if s.helpDefinition == nil {
s.helpDefinition = &CommandDefinition{}
}
if s.helpDefinition.Handler == nil {
s.helpDefinition.Handler = s.defaultHelp
}
if len(s.helpDefinition.Description) == 0 {
s.helpDefinition.Description = helpCommand
}
s.botCommands = append([]BotCommand{NewBotCommand(helpCommand, s.helpDefinition, true, defaultIncludeChannelIds)}, s.botCommands...)
}
func (s *Slacker) handleInteractiveEvent(slacker *Slacker, evt *socketmode.Event, callback *slack.InteractionCallback, req *socketmode.Request) {
for _, cmd := range s.botCommands {
for _, action := range callback.ActionCallback.BlockActions {
if action.BlockID != cmd.Definition().BlockID {
continue
}
cmd.Interactive(slacker, evt, callback, req)
return
}
}
if s.interactiveEventHandler != nil {
s.interactiveEventHandler(slacker, evt, callback)
}
}
func (s *Slacker) handleMessageEvent(ctx context.Context, evt interface{}, req *socketmode.Request) {
if s.botContextConstructor == nil {
s.botContextConstructor = NewBotContext
}
if s.requestConstructor == nil {
s.requestConstructor = NewRequest
}
if s.responseConstructor == nil {
s.responseConstructor = NewResponse
}
ev := newMessageEvent(s, evt, req)
if ev == nil {
// event doesn't appear to be a valid message type
return
} else if ev.IsBot() {
switch s.botInteractionMode {
case BotInteractionModeIgnoreApp:
bot, err := s.client.GetBotInfo(ev.BotID)
if err != nil {
if err.Error() == "missing_scope" {
fmt.Println("unable to determine if bot response is from me -- please add users:read scope to your app")
} else {
fmt.Printf("unable to get bot that sent message information: %v\n", err)
}
return
}
if bot.AppID == s.appID {
fmt.Printf("Ignoring event that originated from my App ID: %v\n", bot.AppID)
return
}
case BotInteractionModeIgnoreAll:
fmt.Printf("Ignoring event that originated from Bot ID: %v\n", ev.BotID)
return
default:
// BotInteractionModeIgnoreNone is handled in the default case
}
}
botCtx := s.botContextConstructor(ctx, s.client, s.socketModeClient, ev)
response := s.responseConstructor(botCtx)
eventTxt := s.cleanEventInput(ev.Text)
var request Request
var parameters []allot.Parameter
var cmdMatch allot.MatchInterface
for _, cmd := range s.botCommands {
if cmd.ContainsChannel(ev.Channel) {
if cmd.IsParameterizedCommand() {
cmdMatches := cmd.Matches(ev.Text)
if !cmdMatches {
continue
}
parameters = cmd.Parameters()
cmdMatch, _ = cmd.Match(eventTxt)
} else {
cmdMatches := cmd.MsgContains(eventTxt)
if !cmdMatches {
continue
}
}
request = s.requestConstructor(botCtx, parameters, cmdMatch)
if cmd.Definition().AuthorizationFunc != nil && !cmd.Definition().AuthorizationFunc(botCtx, request) {
response.ReportError(s.errUnauthorized)
return
}
select {
case s.commandChannel <- NewCommandEvent(cmd.Usage(), parameters, ev):
default:
// full channel, dropped event
}
cmd.Execute(botCtx, request, response)
return
}
}
if s.defaultMessageHandler != nil {
request := s.requestConstructor(botCtx, nil, nil)
s.defaultMessageHandler(botCtx, request, response)
}
}
func getChannelName(slacker *Slacker, channelID string) string {
channel, err := slacker.client.GetConversationInfo(channelID, true)
if err != nil {
fmt.Printf("unable to get channel info for %s: %v\n", channelID, err)
return channelID
}
return channel.Name
}
func getUserName(slacker *Slacker, userID string) string {
user, err := slacker.client.GetUserInfo(userID)
if err != nil {
fmt.Printf("unable to get user info for %s: %v\n", userID, err)
return userID
}
return user.Name
}
func newMessageEvent(slacker *Slacker, evt interface{}, req *socketmode.Request) *MessageEvent {
var me *MessageEvent
switch ev := evt.(type) {
case *slackevents.MessageEvent:
me = &MessageEvent{
Channel: ev.Channel,
ChannelName: getChannelName(slacker, ev.Channel),
User: ev.User,
UserName: getUserName(slacker, ev.User),
Text: ev.Text,
Data: evt,
Type: ev.Type,
TimeStamp: ev.TimeStamp,
ThreadTimeStamp: ev.ThreadTimeStamp,
BotID: ev.BotID,
}
case *slackevents.AppMentionEvent:
me = &MessageEvent{
Channel: ev.Channel,
ChannelName: getChannelName(slacker, ev.Channel),
User: ev.User,
UserName: getUserName(slacker, ev.User),
Text: ev.Text,
Data: evt,
Type: ev.Type,
TimeStamp: ev.TimeStamp,
ThreadTimeStamp: ev.ThreadTimeStamp,
BotID: ev.BotID,
}
case *slack.SlashCommand:
me = &MessageEvent{
Channel: ev.ChannelID,
ChannelName: ev.ChannelName,
User: ev.UserID,
UserName: ev.UserName,
Text: fmt.Sprintf("%s %s", ev.Command[1:], ev.Text),
Data: req,
Type: req.Type,
}
}
// Filter out other bots. At the very least this is needed for MessageEvent
// to prevent the bot from self-triggering and causing loops. However better
// logic should be in place to prevent repeated self-triggering / bot-storms
// if we want to enable this later.
if me.IsBot() {
return nil
}
return me
}