104 lines
2.4 KiB
Go
104 lines
2.4 KiB
Go
package app
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.bullercodeworks.com/brian/helperbot/models"
|
|
"git.bullercodeworks.com/brian/helperbot/plugins"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
type App struct {
|
|
debug bool
|
|
|
|
m *models.BotModel
|
|
|
|
plugins []models.PluginState
|
|
}
|
|
|
|
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
|
|
}
|
|
go a.watchMessageChannel()
|
|
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
|
|
}
|
|
a.m.Running = true
|
|
|
|
// Load up the plugins
|
|
a.plugins = append(a.plugins, &plugins.StatsState{}, &plugins.AoCState{})
|
|
for _, p := range a.plugins {
|
|
p.Initialize(a.m)
|
|
}
|
|
a.setupMessageWatchers()
|
|
for _, p := range a.plugins {
|
|
p.Run()
|
|
}
|
|
|
|
a.m.SendSlackAdminMessage(":robot_face: Helperbot Initialized :robot_face:")
|
|
return err
|
|
}
|
|
|
|
func (a *App) Stop() { a.m.Running = false }
|
|
func (a *App) IsRunning() bool { return a.m.Running }
|
|
|
|
func (a *App) SendQuitMessage() { a.m.SendMessage(models.QuitMessage) }
|
|
|
|
func (a *App) setupMessageWatchers() {
|
|
a.m.AddMessageWatcher("main", func(msg models.BotMessage) bool {
|
|
if msg.Is(models.QuitMessage) {
|
|
// App is shutting down
|
|
fmt.Println("Received QuitMessage")
|
|
a.m.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(fmt.Sprintf("plugin-%s", v.Name()), v.ProcessMessage)
|
|
a.m.AddRTMWatcher(fmt.Sprintf("plugin-%s", v.Name()), v.ProcessRTMEvent)
|
|
}
|
|
}
|
|
|
|
func (a *App) watchMessageChannel() {
|
|
for a.m.Running {
|
|
a.m.ProcessMessageChannel()
|
|
}
|
|
}
|