nunbot/nun.go

98 lines
2.2 KiB
Go

package main
import (
"fmt"
"time"
"github.com/charmbracelet/log"
"maunium.net/go/mautrix"
)
type nunWatch struct {
fail int
curPost post
stop chan bool
client *mautrix.Client
timer int
}
func newNunWatch(stop chan bool, c *mautrix.Client, t int) *nunWatch {
return &nunWatch{0, post{}, stop, c, t}
}
func (n *nunWatch) SetTimer(t int) {
n.timer = t
n.fail = 0
}
func (n *nunWatch) Main() {
ticker := time.NewTicker(time.Duration(n.timer) * time.Minute)
curT := n.timer
for {
select {
case <-n.stop:
return
case <-ticker.C:
newPost, err := getNewestPost("LittleNuns")
if err != nil {
log.Warn("error getting newest post:", "error", err)
log.Warn("skipping this cycle, incrementing fail count")
n.fail++
if n.fail > 5 {
log.Fatal("failgithub.com/charmbracelet/log count too high; ending loop")
return
} else if n.fail > 3 {
log.Warnf("over three failures, increasing tick time to %v minutes", 3*n.timer)
ticker.Reset(3 * time.Duration(n.timer) * time.Minute)
break
} else {
log.Warnf("fail count %v", n.fail)
break
}
}
n.fail = 0
ticker.Reset(time.Duration(n.timer) * time.Minute)
if curT != n.timer {
log.Info("updating nunwatch timer")
ticker.Reset(time.Duration(n.timer) * time.Minute)
n.fail = 0
curT = n.timer
}
if n.curPost.Title != newPost.Title {
n.curPost = newPost
var cur post
err := n.client.GetAccountData("nun.newest", &cur)
if err != nil {
log.Warnf("tried to get saved account data but failed %v", err)
cur.Number = 0
}
roomResp, err := n.client.JoinedRooms()
if err != nil {
log.Warnf("error getting joined rooms: %v", err)
break
}
rooms := roomResp.JoinedRooms
for _, room := range rooms {
if n.curPost.Number != cur.Number {
log.Infof("posting %v", n.curPost.Number)
_, err := n.client.SendText(room, fmt.Sprintf("%v\n%v", n.curPost.Title, n.curPost.Link))
if err != nil {
log.Printf("err sending to room: %v", err)
}
if n.curPost.Number > 0 {
err := n.client.SetAccountData("nun.newest", n.curPost)
if err != nil {
log.Warnf("error saving current post: %v", err)
}
}
}
}
}
}
}
}