-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
369 lines (279 loc) · 11 KB
/
bot.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
/*************************************************************************
* Written by / Copyright (C) 2017 bytemine GmbH *
* Author: Felix Kronlage E-Mail: kronlage@bytemine.net *
* *
* http://www.bytemine.net/ *
*************************************************************************/
// this source was initially based on the mattermost sample bot
// https://github.com/mattermost/mattermost-bot-sample-golang
package main
import (
"net/http"
"plugin"
"fmt"
"log"
"reflect"
"unsafe"
"encoding/json"
"strings"
"github.com/bytemine/mbothelper"
"github.com/gorilla/mux"
"github.com/mattermost/platform/model"
"github.com/spf13/viper"
)
var client *model.Client4
var webSocketClient *model.WebSocketClient
var botUser *model.User
var botTeam *model.Team
var debuggingChannel *model.Channel
var mainChannel *model.Channel
var statusChannel *model.Channel
const MbotVersion = "0.0.1"
var config mbothelper.BotConfig
var helpHandlers map[string]plugin.Symbol
func main() {
log.SetPrefix("[mbot] - ")
log.SetFlags(log.Ldate | log.Lmicroseconds | log.Llongfile)
// look in config/mbot.toml for the config
viper.SetConfigName("mbot")
viper.AddConfigPath("config")
err := viper.ReadInConfig()
if err != nil {
log.Fatalf("Config file not found or error parsing: %v", err)
}
config.MattermostServer = viper.GetString("general.mattermost")
config.MattermostWSURL = viper.GetString("general.wsurl")
config.Listen = viper.GetString("general.listen")
config.BotName = viper.GetString("general.botname")
config.UserEmail = viper.GetString("general.useremail")
config.UserName = viper.GetString("general.username")
config.UserPassword = viper.GetString("general.userpassword")
config.UserLastname = viper.GetString("general.userlastname")
config.UserFirstname = viper.GetString("general.userfirstname")
config.TeamName = viper.GetString("general.teamname")
config.LogChannel = viper.GetString("channel.log")
config.MainChannel = viper.GetString("channel.main")
config.StatusChannel = viper.GetString("channel.status")
config.PluginsDirectory = viper.GetString("general.plugins_directory")
config.Plugins = viper.GetStringSlice("general.plugins")
log.Printf("Using Config:\n%+v", config)
// make sure we exit cleanly upon ctrl-c
mbothelper.SetupGracefulShutdown()
client = model.NewAPIv4Client(config.MattermostServer)
mbothelper.InitMbotHelper(config, client)
// Lets test to see if the mattermost server is up and running
mbothelper.MakeSureServerIsRunning()
// lets attempt to login to the Mattermost server as the bot user
// This will set the token required for all future calls
// You can get this token with client.AuthToken
mbothelper.LoginAsTheBotUser()
// If the bot user doesn't have the correct information lets update his profile
mbothelper.UpdateTheBotUserIfNeeded()
// Lets find our bot team
mbothelper.FindBotTeam()
// Lets create a bot channel for logging debug messages into
mbothelper.CreateBotDebuggingChannelIfNeeded()
mbothelper.SendMsgToDebuggingChannel("_"+config.BotName+" has **started** running_", "")
// Join to main channel...
mbothelper.MainChannel = mbothelper.JoinChannel(config.MainChannel, mbothelper.BotTeam.Id, mbothelper.BotUser.Id)
// ...and our status channel
mbothelper.StatusChannel = mbothelper.JoinChannel(config.StatusChannel, mbothelper.BotTeam.Id, mbothelper.BotUser.Id)
helpHandlers = map[string]plugin.Symbol{}
// for request handler plugins
router := mux.NewRouter()
config.PluginsConfig = make(map[string]mbothelper.BotConfigPlugin)
// iterate over plugins
// each plugin will run in a goroutine
for _, openPlugin := range config.Plugins {
// loading the plugin itself - open the so file to load the symbols
plug, err := plugin.Open(config.PluginsDirectory + openPlugin)
if err != nil {
log.Printf("Plugin %v failed to load: %v", openPlugin, err)
continue
}
inspectPlugin(plug)
keyHandler := fmt.Sprintf("%s.handler", openPlugin)
keyWatcher := fmt.Sprintf("%s.watcher", openPlugin)
keyMentionHandler := fmt.Sprintf("%s.mention_handler", openPlugin)
keyHelpHandler := fmt.Sprintf("%s.help_handler", openPlugin)
pathPatterns := fmt.Sprintf("%s.path_patterns", openPlugin)
pluginConfigFile := fmt.Sprintf("%s.config_file", openPlugin)
channels := fmt.Sprintf("%s.channels", openPlugin)
pluginConfigFileName := ""
if viper.IsSet(pluginConfigFile) {
pluginConfigFileName = viper.GetString(pluginConfigFile)
}
channelList := viper.GetStringSlice(channels)
pluginConfig := mbothelper.BotConfigPlugin{
PluginName: openPlugin,
Handler: viper.GetString(keyHandler),
Watcher: viper.GetString(keyWatcher),
MentionHandler: viper.GetString(keyMentionHandler),
HelpHandler: viper.GetString(keyHelpHandler),
PathPatterns: viper.GetStringSlice(pathPatterns),
PluginConfig: pluginConfigFileName,
Channels: make(map[string]*model.Channel),
}
config.PluginsConfig[openPlugin] = pluginConfig
mbothelper.SendMsgToDebuggingChannel(fmt.Sprintf("Loaded plugin: %s", openPlugin), "")
// we always have a set channels function
pluginHandlerSetChannels, err := plug.Lookup("SetChannels")
if err != nil {
log.Printf("Symbol 'SetChannels' missing from plugin '%v'. Error: %v", openPlugin, err)
continue
}
// if we have a configured config file for the plugin load it
if pluginConfigFileName != "" {
pluginConfigHandler, err := plug.Lookup("LoadConfig")
if err != nil {
log.Printf("Config file '%v' for plugin '%v' failed to process: %v", pluginConfigFileName, openPlugin, err)
continue
}
mbothelper.SendMsgToDebuggingChannel(fmt.Sprintf("Loading configuration file '%s' for plugin: %s",
pluginConfigFileName, openPlugin), "")
pluginConfigHandler.(func(string))(pluginConfigFileName)
}
pluginHandlerSetChannels.(func(string, string, string))(mbothelper.MainChannel.Id, mbothelper.StatusChannel.Id, mbothelper.DebuggingChannel.Id)
// join configured channels for plugin
for _, channel := range channelList {
log.Printf("joining channel: %s\n", channel)
rchannel := mbothelper.JoinChannel(channel, mbothelper.BotTeam.Id, mbothelper.BotUser.Id)
pluginConfig.Channels[channel] = rchannel
mbothelper.SendMsgToDebuggingChannel(fmt.Sprintf("Joined channel '%s'", channel), "")
}
// look up a symbol (an exported function or variable)
if pluginConfig.Handler != "" {
pluginHandler, err := plug.Lookup(pluginConfig.Handler)
if err != nil {
log.Printf("Couldn't lookup handler: %v", err)
continue
}
for _, pathPattern := range pluginConfig.PathPatterns {
msg := fmt.Sprintf("Setting up routing for %s", pathPattern)
mbothelper.SendMsgToDebuggingChannel(msg, "")
router.HandleFunc(pathPattern, pluginHandler.(func(http.ResponseWriter, *http.Request)))
}
go func() { log.Fatal(http.ListenAndServe(config.Listen, router)) }()
}
if pluginConfig.Watcher != "" {
pluginWatcher, err := plug.Lookup(pluginConfig.Watcher)
if err != nil {
log.Printf("Couldn't lookup watcher: %v", err)
continue
}
mbothelper.SendMsgToDebuggingChannel(fmt.Sprintf("Registering watcher for plugin '%s'", openPlugin), "")
go func() {
// create a dedicated websocket client for this go routine
webSocketClient, err := model.NewWebSocketClient(config.MattermostWSURL, client.AuthToken)
if err != nil {
log.Printf("Failed to connect to the web socket: %v", err)
}
webSocketClient.Listen()
for resp := range webSocketClient.EventChannel {
handleWebSocketResponse(resp, pluginWatcher)
}
}()
}
if pluginConfig.MentionHandler != "" {
pluginMentionHandler, err := plug.Lookup(pluginConfig.MentionHandler)
if err != nil {
log.Printf("Couldn't lookup mention handler: %v", err)
continue
}
mbothelper.SendMsgToDebuggingChannel(fmt.Sprintf("Registering mention_handler for plugin '%s'", openPlugin), "")
go func() {
// create a dedicated websocket client for this go routine
webSocketClient, err := model.NewWebSocketClient(config.MattermostWSURL, client.AuthToken)
if err != nil {
log.Printf("Failed to connect to the web socket: %v", err)
}
webSocketClient.Listen()
for resp := range webSocketClient.EventChannel {
handleMention(resp, pluginMentionHandler)
}
}()
}
if pluginConfig.HelpHandler != "" {
pluginHelpHandler, err := plug.Lookup(pluginConfig.HelpHandler)
if err != nil {
log.Printf("Couldn't lookup help handler: %v", err)
}
helpHandlers[pluginConfig.PluginName] = pluginHelpHandler
}
mbothelper.SendMsgToDebuggingChannel(fmt.Sprintf("Done initializing plugin: %s", openPlugin), "")
}
// block
select {}
}
func handleWebSocketResponse(event *model.WebSocketEvent, pluginWatcher plugin.Symbol) {
s, ok := event.Data["post"].(string)
if !ok {
log.Printf("handleWebSocketResponse: type assertion failed, want: string, got: %T", event.Data["post"])
return
}
m := extractPost(s)
pluginWatcher.(func(socketEvent *model.WebSocketEvent, Post *model.Post))(event, m)
}
func handleMention(event *model.WebSocketEvent, pluginMentionHandler plugin.Symbol) {
sMention, ok := event.Data["mentions"].(string)
if !ok {
log.Printf("handleMention: type assertion failed, want: string, got: %T", event.Data["mentions"])
return
}
if strings.Contains(sMention, mbothelper.BotUser.Id) {
sPost, ok := event.Data["post"].(string)
if !ok {
log.Printf("handleMention: type assertion failed, want: string, got: %T", event.Data["post"])
return
}
m := extractPost(sPost)
// if we see 'help' in the message contents
if strings.Contains(m.Message, "help") {
handleHelp(m.UserId, m.Message)
}
pluginMentionHandler.(func(socketEvent *model.WebSocketEvent, Post *model.Post))(event, m)
}
}
type Plug struct {
Path string
_ chan struct{}
Symbols map[string]interface{}
}
func extractPost(eventData string) *model.Post {
j := []uint8(eventData)
var m model.Post
err := json.Unmarshal(j, &m)
if err != nil {
log.Printf("Error decoding json: %+v", err)
}
return &m
}
func handleHelp(userId string, message string) {
helped := false
// see if one of our plugins has a handler for this
for pluginKey := range helpHandlers {
if strings.Contains(message, pluginKey) {
helpHandlers[pluginKey].(func(userId string, message string))(userId, message)
helped = true
break
}
}
if !helped {
// nope, not the case, fire general help
help(userId)
}
}
func help(userId string) {
m := fmt.Sprintf("help - mbot - version: %s\nUse `help <pluginname>` for plugn specific help.\n", MbotVersion)
for plugin := range helpHandlers {
m = fmt.Sprintf("%s\n\t%s", m, plugin)
}
mbothelper.ReplyToUser(m, userId)
}
func inspectPlugin(p *plugin.Plugin) {
pl := (*Plug)(unsafe.Pointer(p))
log.Printf("Plugin %s exported symbols (%d):", pl.Path, len(pl.Symbols))
for name, pointers := range pl.Symbols {
log.Printf("symbol: %s, pointer: %v, type: %v", name, pointers, reflect.TypeOf(pointers))
}
}