-
Notifications
You must be signed in to change notification settings - Fork 119
/
slacker.go
573 lines (482 loc) · 17.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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
package slacker
import (
"context"
"fmt"
"strings"
"github.com/robfig/cron/v3"
"github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
"github.com/slack-go/slack/socketmode"
)
const (
space = " "
dash = "-"
newLine = "\n"
invalidToken = "invalid token"
helpCommand = "help"
codeMessageFormat = "`%s`"
boldMessageFormat = "*%s*"
italicMessageFormat = "_%s_"
exampleMessageFormat = "_*Example:*_ %s"
)
// NewClient creates a new client using the Slack API
func NewClient(botToken, appToken string, clientOptions ...ClientOption) *Slacker {
options := newClientOptions(clientOptions...)
slackOpts := newSlackOptions(appToken, options)
slackAPI := slack.New(botToken, slackOpts...)
socketModeClient := socketmode.New(
slackAPI,
socketmode.OptionDebug(options.Debug),
)
slacker := &Slacker{
slackClient: slackAPI,
socketModeClient: socketModeClient,
cronClient: cron.New(cron.WithLocation(options.CronLocation)),
commandGroups: []*CommandGroup{newGroup("")},
botInteractionMode: options.BotMode,
sanitizeEventTextHandler: defaultEventTextSanitizer,
logger: options.Logger,
interactions: make(map[slack.InteractionType][]*Interaction),
}
return slacker
}
// Slacker contains the Slack API, botCommands, and handlers
type Slacker struct {
slackClient *slack.Client
socketModeClient *socketmode.Client
cronClient *cron.Cron
commandMiddlewares []CommandMiddlewareHandler
commandGroups []*CommandGroup
interactionMiddlewares []InteractionMiddlewareHandler
interactions map[slack.InteractionType][]*Interaction
jobMiddlewares []JobMiddlewareHandler
jobs []*Job
onHello func(socketmode.Event)
onConnected func(socketmode.Event)
onConnecting func(socketmode.Event)
onConnectionError func(socketmode.Event)
onDisconnected func(socketmode.Event)
unsupportedInteractionHandler InteractionHandler
helpDefinition *CommandDefinition
unsupportedCommandHandler CommandHandler
unsupportedEventHandler func(socketmode.Event)
appID string
botInteractionMode BotMode
sanitizeEventTextHandler func(string) string
logger Logger
}
// GetCommandGroups returns Command Groups
func (s *Slacker) GetCommandGroups() []*CommandGroup {
return s.commandGroups
}
// GetInteractions returns Groups
func (s *Slacker) GetInteractions() map[slack.InteractionType][]*Interaction {
return s.interactions
}
// GetJobs returns Jobs
func (s *Slacker) GetJobs() []*Job {
return s.jobs
}
// SlackClient returns the internal slack.Client of Slacker struct
func (s *Slacker) SlackClient() *slack.Client {
return s.slackClient
}
// SocketModeClient returns the internal socketmode.Client of Slacker struct
func (s *Slacker) SocketModeClient() *socketmode.Client {
return s.socketModeClient
}
// OnHello handle the event when slack sends the bot "hello"
func (s *Slacker) OnHello(onHello func(socketmode.Event)) {
s.onHello = onHello
}
// OnConnected handle the event when the bot is connected
func (s *Slacker) OnConnected(onConnected func(socketmode.Event)) {
s.onConnected = onConnected
}
// OnConnecting handle the event when the bot is connecting
func (s *Slacker) OnConnecting(onConnecting func(socketmode.Event)) {
s.onConnecting = onConnecting
}
// OnConnectionError handle the event when the bot fails to connect
func (s *Slacker) OnConnectionError(onConnectionError func(socketmode.Event)) {
s.onConnectionError = onConnectionError
}
// OnDisconnected handle the event when the bot is disconnected
func (s *Slacker) OnDisconnected(onDisconnected func(socketmode.Event)) {
s.onDisconnected = onDisconnected
}
// UnsupportedInteractionHandler handles interactions when none of the callbacks are matched
func (s *Slacker) UnsupportedInteractionHandler(unsupportedInteractionHandler InteractionHandler) {
s.unsupportedInteractionHandler = unsupportedInteractionHandler
}
// UnsupportedCommandHandler handles messages when none of the commands are matched
func (s *Slacker) UnsupportedCommandHandler(unsupportedCommandHandler CommandHandler) {
s.unsupportedCommandHandler = unsupportedCommandHandler
}
// UnsupportedEventHandler handles events when an unknown event is seen
func (s *Slacker) UnsupportedEventHandler(unsupportedEventHandler func(socketmode.Event)) {
s.unsupportedEventHandler = unsupportedEventHandler
}
// SanitizeEventTextHandler overrides the default event text sanitization
func (s *Slacker) SanitizeEventTextHandler(sanitizeEventTextHandler func(in string) string) {
s.sanitizeEventTextHandler = sanitizeEventTextHandler
}
// Help handle the help message, it will use the default if not set
func (s *Slacker) Help(definition *CommandDefinition) {
if len(definition.Command) == 0 {
s.logger.Error("missing `Command`")
return
}
s.helpDefinition = definition
}
// AddCommand define a new command and append it to the list of bot commands
func (s *Slacker) AddCommand(definition *CommandDefinition) {
if len(definition.Command) == 0 {
s.logger.Error("missing `Command`")
return
}
s.commandGroups[0].AddCommand(definition)
}
// AddCommandMiddleware appends a new command middleware to the list of root level command middlewares
func (s *Slacker) AddCommandMiddleware(middleware CommandMiddlewareHandler) {
s.commandMiddlewares = append(s.commandMiddlewares, middleware)
}
// AddCommandGroup define a new group and append it to the list of groups
func (s *Slacker) AddCommandGroup(prefix string) *CommandGroup {
group := newGroup(prefix)
s.commandGroups = append(s.commandGroups, group)
return group
}
// AddInteraction define a new interaction and append it to the list of interactions
func (s *Slacker) AddInteraction(definition *InteractionDefinition) {
if len(definition.InteractionID) == 0 {
s.logger.Error("missing `ID`")
return
}
if len(definition.Type) == 0 {
s.logger.Error("missing `Type`")
return
}
s.interactions[definition.Type] = append(s.interactions[definition.Type], newInteraction(definition))
}
// AddInteractionMiddleware appends a new interaction middleware to the list of root level interaction middlewares
func (s *Slacker) AddInteractionMiddleware(middleware InteractionMiddlewareHandler) {
s.interactionMiddlewares = append(s.interactionMiddlewares, middleware)
}
// AddJob define a new cron job and append it to the list of jobs
func (s *Slacker) AddJob(definition *JobDefinition) {
if len(definition.CronExpression) == 0 {
s.logger.Error("missing `CronExpression`")
return
}
s.jobs = append(s.jobs, newJob(definition))
}
// AddJobMiddleware appends a new job middleware to the list of root level job middlewares
func (s *Slacker) AddJobMiddleware(middleware JobMiddlewareHandler) {
s.jobMiddlewares = append(s.jobMiddlewares, middleware)
}
// 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 socketEvent, ok := <-s.socketModeClient.Events:
if !ok {
return
}
switch socketEvent.Type {
case socketmode.EventTypeConnecting:
s.logger.Infof("connecting to Slack with Socket Mode...\n")
if s.onConnecting == nil {
continue
}
go s.onConnecting(socketEvent)
case socketmode.EventTypeConnectionError:
s.logger.Infof("connection failed. Retrying later...\n")
if s.onConnectionError == nil {
continue
}
go s.onConnectionError(socketEvent)
case socketmode.EventTypeConnected:
s.logger.Infof("connected to Slack with Socket Mode.\n")
if s.onConnected == nil {
continue
}
go s.onConnected(socketEvent)
case socketmode.EventTypeHello:
s.appID = socketEvent.Request.ConnectionInfo.AppID
s.logger.Infof("connected as App ID %v\n", s.appID)
if s.onHello == nil {
continue
}
go s.onHello(socketEvent)
case socketmode.EventTypeDisconnect:
s.logger.Infof("disconnected due to %v\n", socketEvent.Request.Reason)
if s.onDisconnected == nil {
continue
}
go s.onDisconnected(socketEvent)
case socketmode.EventTypeEventsAPI:
event, ok := socketEvent.Data.(slackevents.EventsAPIEvent)
if !ok {
s.logger.Debugf("ignored %+v\n", socketEvent)
continue
}
// Acknowledge receiving the request
s.socketModeClient.Ack(*socketEvent.Request)
if event.Type != slackevents.CallbackEvent {
if s.unsupportedEventHandler != nil {
s.unsupportedEventHandler(socketEvent)
} else {
s.logger.Debugf("unsupported event received %+v\n", socketEvent)
}
continue
}
switch event.InnerEvent.Type {
case "message", "app_mention": // message-based events
go s.handleMessageEvent(ctx, event.InnerEvent.Data)
default:
if s.unsupportedEventHandler != nil {
s.unsupportedEventHandler(socketEvent)
} else {
s.logger.Debugf("unsupported event received %+v\n", socketEvent)
}
}
case socketmode.EventTypeSlashCommand:
event, ok := socketEvent.Data.(slack.SlashCommand)
if !ok {
s.logger.Debugf("ignored %+v\n", socketEvent)
continue
}
// Acknowledge receiving the request
s.socketModeClient.Ack(*socketEvent.Request)
go s.handleMessageEvent(ctx, &event)
case socketmode.EventTypeInteractive:
callback, ok := socketEvent.Data.(slack.InteractionCallback)
if !ok {
s.logger.Debugf("ignored %+v\n", socketEvent)
continue
}
// Acknowledge receiving the request
s.socketModeClient.Ack(*socketEvent.Request)
go s.handleInteractionEvent(ctx, &callback)
default:
if s.unsupportedEventHandler != nil {
s.unsupportedEventHandler(socketEvent)
} else {
s.logger.Debugf("unsupported event received %+v\n", socketEvent)
}
}
}
}
}()
s.startCronJobs(ctx)
defer s.cronClient.Stop()
// 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) defaultHelp(ctx *CommandContext) {
blocks := []slack.Block{}
for _, group := range s.GetCommandGroups() {
for _, command := range group.GetCommands() {
if command.Definition().HideHelp {
continue
}
helpMessage := empty
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)
}
blocks = append(blocks,
slack.NewSectionBlock(
slack.NewTextBlockObject(slack.MarkdownType, helpMessage, false, false),
nil, nil,
))
if len(command.Definition().Examples) > 0 {
examplesMessage := empty
for _, example := range command.Definition().Examples {
examplesMessage += fmt.Sprintf(exampleMessageFormat, example) + newLine
}
blocks = append(blocks, slack.NewContextBlock("",
slack.NewTextBlockObject(slack.MarkdownType, examplesMessage, false, false),
))
}
}
}
if len(s.GetJobs()) == 0 {
ctx.Response().ReplyBlocks(blocks)
return
}
blocks = append(blocks, slack.NewDividerBlock())
for _, job := range s.GetJobs() {
if job.Definition().HideHelp {
continue
}
helpMessage := fmt.Sprintf(codeMessageFormat, job.Definition().CronExpression)
if len(job.Definition().Name) > 0 {
helpMessage += space + dash + space + fmt.Sprintf(codeMessageFormat, job.Definition().Name)
}
if len(job.Definition().Description) > 0 {
helpMessage += space + dash + space + fmt.Sprintf(italicMessageFormat, job.Definition().Description)
}
blocks = append(blocks,
slack.NewSectionBlock(
slack.NewTextBlockObject(slack.MarkdownType, helpMessage, false, false),
nil, nil,
))
}
ctx.Response().ReplyBlocks(blocks)
}
func (s *Slacker) prependHelpHandle() {
if s.helpDefinition == nil {
s.helpDefinition = &CommandDefinition{
Command: helpCommand,
Description: helpCommand,
Handler: s.defaultHelp,
}
}
s.commandGroups[0].PrependCommand(s.helpDefinition)
}
func (s *Slacker) startCronJobs(ctx context.Context) {
middlewares := make([]JobMiddlewareHandler, 0)
middlewares = append(middlewares, s.jobMiddlewares...)
for _, job := range s.jobs {
definition := job.Definition()
middlewares = append(middlewares, definition.Middlewares...)
jobCtx := newJobContext(ctx, s.logger, s.slackClient, definition)
_, err := s.cronClient.AddFunc(definition.CronExpression, executeJob(jobCtx, definition.Handler, middlewares...))
if err != nil {
s.logger.Errorf(err.Error())
}
}
s.cronClient.Start()
}
func (s *Slacker) handleInteractionEvent(ctx context.Context, callback *slack.InteractionCallback) {
middlewares := make([]InteractionMiddlewareHandler, 0)
middlewares = append(middlewares, s.interactionMiddlewares...)
var interaction *Interaction
var definition *InteractionDefinition
switch callback.Type {
case slack.InteractionTypeBlockActions:
for _, i := range s.interactions[callback.Type] {
for _, a := range callback.ActionCallback.BlockActions {
definition = i.Definition()
if a.BlockID == definition.InteractionID {
interaction = i
break
}
}
if interaction != nil {
break
}
}
case slack.InteractionTypeViewClosed, slack.InteractionTypeViewSubmission:
for _, i := range s.interactions[callback.Type] {
definition = i.Definition()
if definition.InteractionID == callback.View.CallbackID {
interaction = i
break
}
}
case slack.InteractionTypeShortcut, slack.InteractionTypeMessageAction:
for _, i := range s.interactions[callback.Type] {
definition = i.Definition()
if definition.InteractionID == callback.CallbackID {
interaction = i
break
}
}
}
if interaction != nil {
interactionCtx := newInteractionContext(ctx, s.logger, s.slackClient, callback, definition)
middlewares = append(middlewares, definition.Middlewares...)
executeInteraction(interactionCtx, definition.Handler, middlewares...)
return
}
s.logger.Debugf("unsupported interaction type received %s\n", callback.Type)
if s.unsupportedInteractionHandler != nil {
interactionCtx := newInteractionContext(ctx, s.logger, s.slackClient, callback, nil)
executeInteraction(interactionCtx, s.unsupportedInteractionHandler, middlewares...)
}
}
func (s *Slacker) handleMessageEvent(ctx context.Context, event any) {
messageEvent := newMessageEvent(s.logger, s.slackClient, event)
if messageEvent == nil {
// event doesn't appear to be a valid message type
return
}
if messageEvent.IsBot() {
if s.ignoreBotMessage(messageEvent) {
return
}
}
middlewares := make([]CommandMiddlewareHandler, 0)
middlewares = append(middlewares, s.commandMiddlewares...)
eventText := s.sanitizeEventTextHandler(messageEvent.Text)
for _, group := range s.commandGroups {
for _, cmd := range group.GetCommands() {
parameters, isMatch := cmd.Match(eventText)
if !isMatch {
continue
}
definition := cmd.Definition()
ctx := newCommandContext(ctx, s.logger, s.slackClient, messageEvent, definition, parameters)
middlewares = append(middlewares, group.GetMiddlewares()...)
middlewares = append(middlewares, definition.Middlewares...)
executeCommand(ctx, definition.Handler, middlewares...)
return
}
}
if s.unsupportedCommandHandler != nil {
ctx := newCommandContext(ctx, s.logger, s.slackClient, messageEvent, nil, nil)
executeCommand(ctx, s.unsupportedCommandHandler, middlewares...)
}
}
func (s *Slacker) ignoreBotMessage(messageEvent *MessageEvent) bool {
switch s.botInteractionMode {
case BotModeIgnoreApp:
bot, err := s.slackClient.GetBotInfo(messageEvent.BotID)
if err != nil {
if err.Error() == "missing_scope" {
s.logger.Errorf("unable to determine if bot response is from me -- please add users:read scope to your app\n")
} else {
s.logger.Debugf("unable to get information on the bot that sent message: %v\n", err)
}
return true
}
if bot.AppID == s.appID {
s.logger.Debugf("ignoring event that originated from my App ID: %v\n", bot.AppID)
return true
}
case BotModeIgnoreAll:
s.logger.Debugf("ignoring event that originated from Bot ID: %v\n", messageEvent.BotID)
return true
default:
// BotInteractionModeIgnoreNone is handled in the default case
}
return false
}
func newSlackOptions(appToken string, options *clientOptions) []slack.Option {
slackOptions := []slack.Option{
slack.OptionDebug(options.Debug),
slack.OptionAppLevelToken(appToken),
}
if len(options.APIURL) > 0 {
slackOptions = append(slackOptions, slack.OptionAPIURL(options.APIURL))
}
return slackOptions
}
func defaultEventTextSanitizer(msg string) string {
return strings.ReplaceAll(msg, "\u00a0", " ")
}