forked from shomali11/slacker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slacker.go
276 lines (228 loc) · 7.54 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
package slacker
import (
"context"
"errors"
"fmt"
"strings"
"github.com/nlopes/slack"
"github.com/shomali11/proper"
)
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 (
unAuthorizedError = errors.New("You are not authorized to execute this command")
)
// NewClient creates a new client using the Slack API
func NewClient(token string, options ...ClientOption) *Slacker {
defaults := newClientDefaults(options...)
client := slack.New(token, slack.OptionDebug(defaults.Debug))
slacker := &Slacker{
client: client,
rtm: client.NewRTM(),
}
return slacker
}
// Slacker contains the Slack API, botCommands, and handlers
type Slacker struct {
client *slack.Client
rtm *slack.RTM
botCommands []BotCommand
requestConstructor func(ctx context.Context, event *slack.MessageEvent, properties *proper.Properties) Request
responseConstructor func(channel string, client *slack.Client, rtm *slack.RTM) ResponseWriter
initHandler func()
errorHandler func(err string)
helpDefinition *CommandDefinition
defaultMessageHandler func(request Request, response ResponseWriter)
defaultEventHandler func(interface{})
unAuthorizedError error
}
// 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
}
// RTM returns returns the internal slack.RTM of Slacker struct
func (s *Slacker) RTM() *slack.RTM {
return s.rtm
}
// 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
}
// CustomRequest creates a new request
func (s *Slacker) CustomRequest(requestConstructor func(ctx context.Context, event *slack.MessageEvent, properties *proper.Properties) Request) {
s.requestConstructor = requestConstructor
}
// CustomResponse creates a new response writer
func (s *Slacker) CustomResponse(responseConstructor func(channel string, client *slack.Client, rtm *slack.RTM) ResponseWriter) {
s.responseConstructor = responseConstructor
}
// DefaultCommand handle messages when none of the commands are matched
func (s *Slacker) DefaultCommand(defaultMessageHandler func(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(unAuthorizedError error) {
s.unAuthorizedError = unAuthorizedError
}
// 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))
}
// Listen receives events from Slack and each is handled as needed
func (s *Slacker) Listen(ctx context.Context) error {
s.prependHelpHandle()
go s.rtm.ManageConnection()
for {
select {
case <-ctx.Done():
s.rtm.Disconnect()
return ctx.Err()
case msg, ok := <-s.rtm.IncomingEvents:
if !ok {
return nil
}
switch event := msg.Data.(type) {
case *slack.ConnectedEvent:
if s.initHandler == nil {
continue
}
go s.initHandler()
case *slack.MessageEvent:
if s.isFromBot(event) {
continue
}
if !s.isBotMentioned(event) && !s.isDirectMessage(event) {
continue
}
go s.handleMessage(ctx, event)
case *slack.RTMError:
if s.errorHandler == nil {
continue
}
go s.errorHandler(event.Error())
case *slack.InvalidAuthEvent:
return errors.New(invalidToken)
default:
if s.defaultEventHandler == nil {
continue
}
go s.defaultEventHandler(event)
}
}
}
return nil
}
// GetUserInfo retrieve complete user information
func (s *Slacker) GetUserInfo(user string) (*slack.User, error) {
return s.client.GetUserInfo(user)
}
func (s *Slacker) sendMessage(text string, channel string) {
s.rtm.SendMessage(s.rtm.NewOutgoingMessage(text, channel))
}
func (s *Slacker) isFromBot(event *slack.MessageEvent) bool {
info := s.rtm.GetInfo()
return len(event.User) == 0 || event.User == slackBotUser || event.User == info.User.ID || len(event.BotID) > 0
}
func (s *Slacker) isBotMentioned(event *slack.MessageEvent) bool {
info := s.rtm.GetInfo()
return strings.Contains(event.Text, fmt.Sprintf(userMentionFormat, info.User.ID))
}
func (s *Slacker) isDirectMessage(event *slack.MessageEvent) bool {
return strings.HasPrefix(event.Channel, directChannelMarker)
}
func (s *Slacker) handleMessage(ctx context.Context, event *slack.MessageEvent) {
if s.requestConstructor == nil {
s.requestConstructor = NewRequest
}
if s.responseConstructor == nil {
s.responseConstructor = NewResponse
}
response := s.responseConstructor(event.Channel, s.client, s.rtm)
for _, cmd := range s.botCommands {
parameters, isMatch := cmd.Match(event.Text)
if !isMatch {
continue
}
request := s.requestConstructor(ctx, event, parameters)
if cmd.Definition().AuthorizationFunc != nil && !cmd.Definition().AuthorizationFunc(request) {
response.ReportError(unAuthorizedError)
}
cmd.Execute(request, response)
return
}
if s.defaultMessageHandler != nil {
request := s.requestConstructor(ctx, event, &proper.Properties{})
s.defaultMessageHandler(request, response)
}
}
func (s *Slacker) defaultHelp(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)}, s.botCommands...)
}