helperbot/plugins_src/plugin_stats.go

90 lines
1.8 KiB
Go
Raw Normal View History

2019-11-22 18:37:15 +00:00
package main
import (
"C"
)
import (
"strings"
"time"
"git.bullercodeworks.com/brian/helperbot"
"github.com/nlopes/slack"
)
type StatsState struct {
model helperbot.Model
lag time.Duration
}
var State StatsState
/* Plugin Interface Functions */
func (s *StatsState) Name() string { return "slack-stats" }
func (s *StatsState) Initialize(m helperbot.Model) error {
s.model = m
return nil
}
func (s *StatsState) ProcessMessage(m helperbot.Message) {
if m.GetSource() == "slack" {
slackMsg := m.GetMessage()
if len(slackMsg.Channel) == 0 {
return
}
admin, err := s.model.GetSlackAdminDMId()
if err != nil {
s.SendAdminIdError()
return
}
if slackMsg.Channel == admin {
s.ProcessAdminDirectMessage(slackMsg)
}
}
}
func (s *StatsState) ProcessRTMEvent(msg slack.RTMEvent) {
switch ev := msg.Data.(type) {
case *slack.LatencyReport:
s.lag = ev.Value
}
}
func (s *StatsState) Run() {}
func (s *StatsState) Exit() {}
/* Other Functions */
func (s *StatsState) ProcessAdminDirectMessage(slackMsg slack.Message) {
msgPts := strings.Fields(slackMsg.Text)
if len(msgPts) < 2 || msgPts[0] != "!stats" {
return
}
switch msgPts[1] {
case "lag", "latency":
s.DoLatencyCommand(slackMsg)
}
}
func (s *StatsState) DoLatencyCommand(slackMsg slack.Message) {
if s.lag == 0 {
s.SendSlackMessage("Unknown", slackMsg.Channel)
return
}
s.SendSlackMessage(s.lag.String(), slackMsg.Channel)
}
func (s *StatsState) SendSlackMessage(text, dest string) {
s.model.SendMessage(s.Name(), "slack", s.BuildMessage("message", text, dest))
}
func (s *StatsState) SendAdminIdError() {
s.model.SendMessage(s.Name(), "error", s.BuildMessage("error", "Error getting Admin DM Id", ""))
}
func (s *StatsState) BuildMessage(tp, text, ch string) slack.Message {
ret := slack.Message{}
ret.Type = tp
ret.Text = text
ret.Channel = ch
return ret
}