catbase/plugins/countdown/countdown.go

116 lines
2.5 KiB
Go
Raw Normal View History

2020-07-13 20:58:44 +00:00
// Countdown is a plugin to do tasks on various milestones.
package countdown
import (
"fmt"
2021-12-20 17:40:10 +00:00
bh "github.com/timshannon/bolthold"
2021-12-22 18:52:16 +00:00
"github.com/velour/catbase/plugins/babbler"
"github.com/velour/catbase/plugins/counter"
2020-07-13 20:58:44 +00:00
"time"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot"
"github.com/velour/catbase/config"
)
2020-12-31 17:36:48 +00:00
var nextYear = time.Date(time.Now().Year()+1, time.January, 1, 0, 0, 0, 1, time.Local)
2020-11-30 19:55:35 +00:00
var thisYear = time.Now().Year()
2020-07-13 20:58:44 +00:00
type CountdownPlugin struct {
2021-12-20 17:40:10 +00:00
b bot.Bot
store *bh.Store
c *config.Config
2020-07-13 20:58:44 +00:00
}
func New(b bot.Bot) *CountdownPlugin {
p := &CountdownPlugin{
2021-12-20 17:40:10 +00:00
b: b,
store: b.Store(),
c: b.Config(),
2020-07-13 20:58:44 +00:00
}
p.scheduleNYE(p.newYearRollover)
return p
}
func (p *CountdownPlugin) scheduleNYE(f func()) {
time.AfterFunc(nextYear.Sub(time.Now()), f)
for i := 10; i > 0; i-- {
mkFunc := func(i int) func() {
return func() {
p.nyeCountdown(i)
}
}
time.AfterFunc(nextYear.Add(time.Duration(10-i)*time.Second).Sub(time.Now()), mkFunc(i))
}
}
func (p *CountdownPlugin) newYearRollover() {
log.Debug().Msgf("Happy new year!")
2021-12-22 18:52:16 +00:00
if err := p.clearBabblers(); err != nil {
log.Error().Err(err).Msgf("error clearing babblers")
}
2020-07-13 20:58:44 +00:00
2021-12-22 18:52:16 +00:00
if err := p.archiveCounters(); err != nil {
log.Error().Err(err).Msgf("error clearing babblers")
2020-07-13 20:58:44 +00:00
}
}
func (p *CountdownPlugin) nyeCountdown(i int) {
chs := p.c.GetArray("channels", []string{})
for _, ch := range chs {
msg := fmt.Sprintf("%d!", i)
p.b.Send(p.b.DefaultConnector(), bot.Message, ch, msg, msg)
}
}
2021-12-22 18:52:16 +00:00
func (p *CountdownPlugin) clearBabblers() error {
if err := p.store.DeleteMatching(babbler.Babbler{}, &bh.Query{}); err != nil {
return err
}
if err := p.store.DeleteMatching(babbler.BabblerArc{}, &bh.Query{}); err != nil {
return err
}
if err := p.store.DeleteMatching(babbler.BabblerNode{}, &bh.Query{}); err != nil {
return err
}
if err := p.store.DeleteMatching(babbler.BabblerWord{}, &bh.Query{}); err != nil {
return err
}
return nil
}
type counterArchive struct {
counter.Item
Year int
}
func (ca counterArchive) Key() string {
return fmt.Sprintf("%d-%d", ca.Year, ca.ID)
}
func (p *CountdownPlugin) archiveCounters() error {
year := time.Now().Year()
allCounters := []counter.Item{}
if err := p.store.Find(&allCounters, &bh.Query{}); err != nil {
return err
}
for _, c := range allCounters {
ca := counterArchive{c, year}
err := p.store.Insert(ca.Key(), ca)
if err != nil {
return err
}
}
if err := p.store.DeleteMatching(counter.Item{}, &bh.Query{}); err != nil {
return err
}
return nil
}