nunbot/nun.go

82 lines
1.7 KiB
Go
Raw Permalink Normal View History

2022-07-17 18:15:29 -04:00
package main
import (
"fmt"
"log"
"time"
"maunium.net/go/mautrix"
)
type nunWatch struct {
fail int
curPost post
stop chan bool
client *mautrix.Client
}
func newNunWatch(stop chan bool, c *mautrix.Client) *nunWatch {
return &nunWatch{0, post{}, stop, c}
}
func (n *nunWatch) Main() {
2022-07-29 16:04:18 -04:00
ticker := time.NewTicker(60 * time.Second)
2022-07-17 18:15:29 -04:00
for {
select {
case <-n.stop:
return
case <-ticker.C:
if n.fail > 5 {
log.Fatal("fail count too high; ending loop")
return
}
if n.fail > 3 {
log.Println("over three failures, increasing tick time to 5 minutes")
ticker.Reset(5 * time.Minute)
continue
}
2022-07-17 18:15:29 -04:00
newPost, err := getNewestPost("LittleNuns")
if err != nil {
log.Printf("error getting newest post: %v", err)
log.Println("skipping this cycle, incrementing fail count")
n.fail++
continue
}
if n.fail != 0 {
n.fail = 0
2022-07-29 16:02:23 -04:00
ticker.Reset(60 * time.Second)
}
2022-07-17 18:15:29 -04:00
if n.curPost.Title != newPost.Title {
n.curPost = newPost
2022-07-29 16:02:23 -04:00
var cur post
err := n.client.GetAccountData("nun.newest", &cur)
if err != nil {
log.Printf("tried to get saved account data but failed %v", err)
cur.Number = 0
}
2022-07-17 18:15:29 -04:00
roomResp, err := n.client.JoinedRooms()
if err != nil {
log.Printf("error getting joined rooms: %v", err)
continue
}
rooms := roomResp.JoinedRooms
for _, room := range rooms {
2022-07-29 16:02:23 -04:00
log.Printf("posting %v", n.curPost.Number)
if n.curPost.Number != cur.Number {
n.client.SendText(room, fmt.Sprintf("%v\n%v", n.curPost.Title, n.curPost.Link))
if n.curPost.Number > 0 {
err := n.client.SetAccountData("nun.newest", n.curPost)
if err != nil {
log.Printf("error saving current post: %v", err)
}
}
}
2022-07-17 18:15:29 -04:00
}
}
}
}
}