From fe28bef7b9615254567b98a37255c20e5395b214 Mon Sep 17 00:00:00 2001 From: Steve Date: Fri, 29 Jul 2022 16:02:23 -0400 Subject: [PATCH] use account data --- nun.go | 21 ++++++++++++++++++--- reddit.go | 19 ++++++++++++++----- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/nun.go b/nun.go index 62e1d0c..1595197 100644 --- a/nun.go +++ b/nun.go @@ -20,7 +20,7 @@ func newNunWatch(stop chan bool, c *mautrix.Client) *nunWatch { } func (n *nunWatch) Main() { - ticker := time.NewTicker(30 * time.Second) + ticker := time.NewTicker(6 * time.Second) for { select { @@ -45,11 +45,17 @@ func (n *nunWatch) Main() { } if n.fail != 0 { n.fail = 0 - ticker.Reset(30 * time.Second) + ticker.Reset(60 * time.Second) } if n.curPost.Title != newPost.Title { n.curPost = newPost + 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 + } roomResp, err := n.client.JoinedRooms() if err != nil { log.Printf("error getting joined rooms: %v", err) @@ -57,7 +63,16 @@ func (n *nunWatch) Main() { } rooms := roomResp.JoinedRooms for _, room := range rooms { - n.client.SendText(room, fmt.Sprintf("%v\n%v", n.curPost.Title, n.curPost.Link)) + 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) + } + } + } } } diff --git a/reddit.go b/reddit.go index d9a37b6..7741c2b 100644 --- a/reddit.go +++ b/reddit.go @@ -6,16 +6,20 @@ import ( "fmt" "io/ioutil" "net/http" + "regexp" + "strconv" "time" ) type post struct { - Title string - Link string + Title string + Link string + Number int } func getNewestPost(subreddit string) (post, error) { var resp redditResp + re := regexp.MustCompile("([0-9]+)") //building request from scratch because reddit api is weird url := fmt.Sprintf("https://www.reddit.com/r/%v/new.json?sort=new&limit=1", subreddit) req, _ := http.NewRequest("GET", url, nil) @@ -43,9 +47,14 @@ func getNewestPost(subreddit string) (post, error) { if err != nil { return post{}, err } - + numS := re.FindStringSubmatch(resp.Data.Children[0].Data.Title)[0] + num, err := strconv.Atoi(numS) + if err != nil || numS == "" { + num = -1 + } return post{ - Title: resp.Data.Children[0].Data.Title, - Link: resp.Data.Children[0].Data.URL, + Title: resp.Data.Children[0].Data.Title, + Link: resp.Data.Children[0].Data.URL, + Number: num, }, nil }