1
0
Fork 0
mirror of https://git.sr.ht/~ashkeel/strimertul synced 2024-09-30 02:40:33 +00:00
strimertul/twitch/alerts/module.go

86 lines
2.1 KiB
Go
Raw Normal View History

2024-03-10 16:38:18 +00:00
package alerts
import (
2024-03-12 22:39:18 +00:00
"context"
"encoding/json"
"log/slog"
2024-03-10 16:38:18 +00:00
"sync"
"text/template"
"git.sr.ht/~ashkeel/strimertul/database"
2024-03-12 23:50:59 +00:00
"git.sr.ht/~ashkeel/strimertul/twitch/eventsub"
template2 "git.sr.ht/~ashkeel/strimertul/twitch/template"
2024-03-10 16:38:18 +00:00
)
type (
templateCache map[string]*template.Template
templateCacheMap map[templateType]templateCache
)
type templateType string
const (
templateTypeSubscription templateType = "subscription"
templateTypeFollow templateType = "follow"
templateTypeRaid templateType = "raid"
templateTypeCheer templateType = "cheer"
templateTypeGift templateType = "gift"
)
type Module struct {
Config Config
2024-03-12 22:39:18 +00:00
ctx context.Context
2024-03-10 16:38:18 +00:00
db database.Database
logger *slog.Logger
2024-03-10 16:38:18 +00:00
templater template2.Engine
templates templateCacheMap
pendingMux sync.Mutex
pendingSubs map[string]subMixedEvent
}
func Setup(ctx context.Context, db database.Database, logger *slog.Logger, templater template2.Engine) *Module {
2024-03-10 16:38:18 +00:00
mod := &Module{
2024-03-12 22:39:18 +00:00
ctx: ctx,
2024-03-10 16:38:18 +00:00
db: db,
logger: logger,
templater: templater,
pendingMux: sync.Mutex{},
pendingSubs: make(map[string]subMixedEvent),
}
// Load config from database
2024-03-12 23:50:59 +00:00
if err := db.GetJSON(ConfigKey, &mod.Config); err != nil {
logger.Debug("Config load error", "error", err)
2024-03-10 16:38:18 +00:00
mod.Config = Config{}
// Save empty config
err = db.PutJSON(ConfigKey, mod.Config)
if err != nil {
logger.Warn("Could not save default config for bot alerts", "error", err)
2024-03-10 16:38:18 +00:00
}
}
mod.compileTemplates()
2024-03-12 23:50:59 +00:00
if err := db.SubscribeKeyContext(ctx, ConfigKey, func(value string) {
err := json.Unmarshal([]byte(value), &mod.Config)
2024-03-10 16:38:18 +00:00
if err != nil {
logger.Warn("Error loading alert config", "error", err)
2024-03-10 16:38:18 +00:00
} else {
logger.Info("Reloaded alert config")
}
mod.compileTemplates()
2024-03-12 23:50:59 +00:00
}); err != nil {
logger.Error("Could not set-up bot alert reload subscription", "error", err)
2024-03-10 16:38:18 +00:00
}
2024-03-12 23:50:59 +00:00
if err := db.SubscribePrefixContext(ctx, mod.onEventSubEvent, eventsub.EventKeyPrefix); err != nil {
logger.Error("Could not setup twitch alert subscription", "error", err)
2024-03-10 16:38:18 +00:00
}
logger.Debug("Loaded bot alerts")
return mod
}