100 lines
2.1 KiB
Go
100 lines
2.1 KiB
Go
|
package app
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"os"
|
||
|
|
||
|
"git.bullercodeworks.com/brian/helperbot/models"
|
||
|
"github.com/spf13/viper"
|
||
|
)
|
||
|
|
||
|
type App struct {
|
||
|
debug bool
|
||
|
Running bool
|
||
|
|
||
|
m *models.BotModel
|
||
|
|
||
|
plugins []HelperPlugin
|
||
|
}
|
||
|
|
||
|
func NewApp(debugMode bool) (*App, error) {
|
||
|
a := new(App)
|
||
|
if debugMode {
|
||
|
fmt.Println("Running in Debug Mode. All messages will be sent to Admin DM")
|
||
|
}
|
||
|
a.debug = debugMode
|
||
|
|
||
|
err := a.initialize()
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
a.Running = true
|
||
|
return a, err
|
||
|
}
|
||
|
|
||
|
func (a *App) initialize() error {
|
||
|
var err error
|
||
|
viper.SetConfigName("config")
|
||
|
viper.SetConfigType("yaml")
|
||
|
viper.AddConfigPath(".")
|
||
|
if err = viper.ReadInConfig(); err != nil {
|
||
|
fmt.Println("Config Read Error...")
|
||
|
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
|
||
|
fmt.Println("Config not found, creating")
|
||
|
// Config file not found; create it
|
||
|
viper.WriteConfigAs("config.yaml")
|
||
|
} else {
|
||
|
// Config file was found but another error was produced
|
||
|
fmt.Println("Other config err:", err)
|
||
|
return err
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if a.m, err = models.NewBotModel(a.debug); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
// Load up the plugins
|
||
|
pluginDir := a.m.GetPluginDir()
|
||
|
a.loadPluginsFromDirectory(pluginDir)
|
||
|
if err != nil {
|
||
|
fmt.Println("Error loading plugins")
|
||
|
fmt.Println(err.Error())
|
||
|
os.Exit(1)
|
||
|
}
|
||
|
a.setupMessageWatchers()
|
||
|
|
||
|
a.m.SendSlackAdminMessage(":robot_face: Helperbot Initialized :robot_face:")
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
func (a *App) SendQuitMessage() { a.m.SendMessage(models.QuitMessage) }
|
||
|
|
||
|
func (a *App) setupMessageWatchers() {
|
||
|
a.m.AddMessageWatcher(func(msg models.BotMessage) bool {
|
||
|
if msg.Is(models.QuitMessage) {
|
||
|
// App is shutting down
|
||
|
a.Running = false
|
||
|
} else if msg.IsError() {
|
||
|
// Received an Error Message
|
||
|
fmt.Printf("ERROR: %s\n", msg)
|
||
|
} else if msg.Dest == models.MsgSrcSlack {
|
||
|
// Sending a message to a slack channel
|
||
|
a.m.SendSlackChannelMessage(msg.Text, msg.Target)
|
||
|
return true
|
||
|
}
|
||
|
return false
|
||
|
})
|
||
|
|
||
|
for _, v := range a.plugins {
|
||
|
a.m.AddMessageWatcher(v.State.ProcessMessage)
|
||
|
a.m.AddRTMWatcher(v.State.ProcessRTMEvent)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (a *App) watchMessageChannel() {
|
||
|
for a.Running {
|
||
|
a.m.ProcessMessageChannel()
|
||
|
}
|
||
|
}
|