forked from shomali11/slacker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslacker.go
384 lines (327 loc) · 10.9 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
package slacker
import (
"context"
"errors"
"fmt"
"regexp"
"github.com/shomali11/commander"
"github.com/shomali11/proper"
"github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
"github.com/slack-go/slack/socketmode"
)
const (
space = " "
dash = "-"
star = "*"
newLine = "\n"
invalidToken = "invalid token"
helpCommand = "help"
directChannelMarker = "D"
userMentionFormat = "<@%s>"
codeMessageFormat = "`%s`"
boldMessageFormat = "*%s*"
italicMessageFormat = "_%s_"
quoteMessageFormat = ">_*Example:* %s_"
authorizedUsersOnly = "Authorized users only"
slackBotUser = "USLACKBOT"
)
var (
errUnauthorized = errors.New("you are not authorized to execute this command")
removeUserRegex = regexp.MustCompile(`^(\s+)?(<@U.*>)(.+)$`)
replaceUserStr = "${1}${3}"
)
// 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,
}
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
requestConstructor func(botCtx BotContext, properties *proper.Properties) 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
}
// 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
}
// Interactive assigns an interactive event handler
func (s *Slacker) Interactive(interactiveEventHandler func(*Slacker, *socketmode.Event, *slack.InteractionCallback)) {
s.interactiveEventHandler = interactiveEventHandler
}
// CustomRequest creates a new request
func (s *Slacker) CustomRequest(requestConstructor func(botCtx BotContext, properties *proper.Properties) 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))
}
// 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)
default:
fmt.Printf("unsupported inner event: %+v\n", ev.InnerEvent.Type)
}
s.socketModeClient.Ack(*evt.Request)
case socketmode.EventTypeInteractive:
if s.interactiveEventHandler == nil {
s.unsupportedEventReceived()
continue
}
callback, ok := evt.Data.(slack.InteractionCallback)
if !ok {
fmt.Printf("Ignored %+v\n", evt)
continue
}
go s.interactiveEventHandler(s, &evt, &callback)
default:
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 {
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
if len(command.Definition().Example) > 0 {
helpMessage += fmt.Sprintf(quoteMessageFormat, command.Definition().Example) + newLine
}
}
if authorizedCommandAvailable {
helpMessage += fmt.Sprintf(codeMessageFormat, star+space+authorizedUsersOnly) + newLine
}
response.Reply(helpMessage)
}
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, commander.WithExactMatch(true))}, s.botCommands...)
}
func (s *Slacker) handleMessageEvent(ctx context.Context, evt interface{}) {
if s.botContextConstructor == nil {
s.botContextConstructor = NewBotContext
}
if s.requestConstructor == nil {
s.requestConstructor = NewRequest
}
if s.responseConstructor == nil {
s.responseConstructor = NewResponse
}
ev := newMessageEvent(evt)
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", 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)
for _, cmd := range s.botCommands {
parameters, isMatch := cmd.Match(ev.Text)
if !isMatch {
continue
}
request := s.requestConstructor(botCtx, parameters)
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)
s.defaultMessageHandler(botCtx, request, response)
}
}
func newMessageEvent(evt interface{}) *MessageEvent {
var me *MessageEvent
switch ev := evt.(type) {
case *slackevents.MessageEvent:
me = &MessageEvent{
Channel: ev.Channel,
User: 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,
User: ev.User,
Text: removeUserRegex.ReplaceAllString(ev.Text, replaceUserStr),
Data: evt,
Type: ev.Type,
TimeStamp: ev.TimeStamp,
ThreadTimeStamp: ev.ThreadTimeStamp,
BotID: ev.BotID,
}
}
return me
}