loadmaster2k/cmd/bot.go

86 lines
1.7 KiB
Go
Raw Normal View History

2020-10-28 11:33:38 +01:00
package cmd
import (
"errors"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"time"
"udico.de/uditaren/goboter"
"udico.de/uditaren/loadmaster2k/api"
"udico.de/uditaren/terminator"
. "udico.de/uditaren/loadmaster2k/config"
)
var cBot = &cobra.Command{
Use: "bot",
Short: "Run the bot",
}
func init() {
cBot.RunE = executeBot
cRoot.AddCommand(cBot)
}
type Load struct {
Area *Area
Load int
Status string
Err error
}
func (l Load) String() string {
if l.Err != nil {
return fmt.Sprintf("%v: error='%v'", l.Area, l.Err.Error())
}
return fmt.Sprintf("%v: load=%v%%, status='%v'", l.Area, l.Load, l.Status)
}
func executeBot(cmd *cobra.Command, args []string) error {
log.Info("Starting bot")
defer log.Info("Bot done")
if C.Bot.Token == "" {
return errors.New("missing bot api token")
}
log.Debugf("Checking state every %v seconds", C.Bot.Interval)
tTickC := time.NewTicker(time.Second * time.Duration(C.Bot.Interval)).C
waiter:
for {
// handle here to simulate an "initial tick"
log.Debug("Tick...")
loads := make([]*Load, 0, 5)
for i, area := range C.Areas {
log.Debugf("Fetching load data for %v", area)
tLoad := &Load{
Area: &C.Areas[i],
}
tData, err := api.FetchArea(area.Id)
if err != nil {
tLoad.Err = err
continue
} else {
tLoad.Load, tLoad.Status = api.ParseAreaStatus(tData)
}
loads = append(loads, tLoad)
log.Info(tLoad)
}
// we're all set: update the bots channel(s)
bot := goboter.NewTelegramBot(C.Bot.Token, "loadmaster2k")
bot.
select {
case <-tTickC:
continue
case <-terminator.Terminate:
log.Info("Terminating bot")
break waiter
}
}
return nil
}