helperbot/models/model.go

98 lines
2.2 KiB
Go
Raw Permalink Normal View History

2023-11-30 18:40:06 +00:00
package models
import (
"fmt"
"time"
"git.bullercodeworks.com/brian/boltease"
"github.com/slack-go/slack"
)
type BotModel struct {
debug bool
db *boltease.DB
messages chan BotMessage
slackApiToken string
slackApi *slack.Client
slackRTM *slack.RTM
slackRTMLatency time.Duration
incomingSlackMessages chan *slack.MessageEvent
otherRTMEvents chan *slack.RTMEvent
2023-12-01 15:26:25 +00:00
messageWatchers map[string]func(msg BotMessage) bool
rtmWatchers map[string]func(event *slack.RTMEvent) bool
2023-12-01 16:57:15 +00:00
Running bool
2023-11-30 18:40:06 +00:00
}
func NewBotModel(debug bool) (*BotModel, error) {
var err error
m := new(BotModel)
m.debug = debug
m.messages = make(chan BotMessage, 100)
2023-12-01 15:26:25 +00:00
m.messageWatchers = make(map[string]func(msg BotMessage) bool)
m.rtmWatchers = make(map[string]func(even *slack.RTMEvent) bool)
m.AddMessageWatcher("debug", m.DebugMessageWatcher)
m.AddRTMWatcher("debug", m.DebugRTMWatcher)
2023-11-30 18:40:06 +00:00
m.db, err = boltease.Create("helperbot.db", 0600, nil)
if err != nil {
return nil, err
}
if err = m.NewSlack(); err != nil {
return nil, err
}
go m.monitorSlackMessages()
return m, nil
}
func (m *BotModel) DebugMessageWatcher(msg BotMessage) bool {
if m.debug {
fmt.Printf("Received Message: %s\n", msg)
}
return false
}
func (m *BotModel) DebugRTMWatcher(event *slack.RTMEvent) bool {
if m.debug {
fmt.Printf("RTMEvent: %s\n", event)
}
return false
}
func (m *BotModel) SendMessage(msg BotMessage) {
2023-12-01 16:57:15 +00:00
if m.debug {
fmt.Println("Sending:", msg)
}
2023-11-30 18:40:06 +00:00
m.messages <- msg
}
2023-12-01 15:26:25 +00:00
func (m *BotModel) AddMessageWatcher(name string, watcher func(msg BotMessage) bool) {
m.messageWatchers[name] = watcher
2023-11-30 18:40:06 +00:00
}
2023-12-01 15:26:25 +00:00
func (m *BotModel) AddRTMWatcher(name string, watcher func(event *slack.RTMEvent) bool) {
m.rtmWatchers[name] = watcher
2023-11-30 18:40:06 +00:00
}
func (m *BotModel) ProcessMessageChannel() {
msg := <-m.messages
2023-12-01 16:57:15 +00:00
for _, v := range m.messageWatchers {
2023-11-30 18:40:06 +00:00
// Pass the message to the watcher
2023-12-01 15:26:25 +00:00
if v != nil && v(msg) {
2023-11-30 18:40:06 +00:00
// if a watcher returns true, the message was consumed
break
}
}
}
func (m *BotModel) ProcessRTMChannel() {
msg := <-m.otherRTMEvents
2023-12-01 16:57:15 +00:00
for _, v := range m.rtmWatchers {
2023-11-30 18:40:06 +00:00
// Pass the event to the watcher
if v(msg) {
// if a watcher returns true, the message was consumed
break
}
}
}