nunbot/reddit.go

69 lines
1.5 KiB
Go
Raw Normal View History

2022-07-13 15:07:01 -04:00
package main
import (
"crypto/tls"
"encoding/json"
2022-11-12 12:55:14 -05:00
"errors"
2022-07-13 15:07:01 -04:00
"fmt"
2023-10-10 21:01:01 -04:00
"io"
2022-07-13 15:07:01 -04:00
"net/http"
2022-07-29 16:02:23 -04:00
"regexp"
"strconv"
2022-07-13 15:07:01 -04:00
"time"
)
type post struct {
2022-07-29 16:02:23 -04:00
Title string
Link string
Number int
2022-07-13 15:07:01 -04:00
}
2022-07-17 18:15:29 -04:00
func getNewestPost(subreddit string) (post, error) {
2022-07-13 15:07:01 -04:00
var resp redditResp
2022-07-29 16:02:23 -04:00
re := regexp.MustCompile("([0-9]+)")
2023-10-10 21:01:01 -04:00
// building request from scratch because reddit api is weird
2022-07-13 15:07:01 -04:00
url := fmt.Sprintf("https://www.reddit.com/r/%v/new.json?sort=new&limit=1", subreddit)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("User-Agent", "Custom Agent")
req.Header.Set("Host", "reddit.com")
2023-10-10 21:01:01 -04:00
defaultClient := http.Client{
2022-07-13 15:07:01 -04:00
Transport: &http.Transport{
TLSNextProto: map[string]func(authority string, c *tls.Conn) http.RoundTripper{},
},
}
res, err := defaultClient.Do(req)
if err != nil {
time.Sleep(5 * time.Second)
res, err = http.Get(url)
if err != nil {
2022-07-17 18:15:29 -04:00
return post{}, err
2022-07-13 15:07:01 -04:00
}
}
defer res.Body.Close()
2023-10-10 21:01:01 -04:00
body, readErr := io.ReadAll(res.Body)
2022-07-13 15:07:01 -04:00
if readErr != nil {
2022-07-17 18:15:29 -04:00
return post{}, err
2022-07-13 15:07:01 -04:00
}
err = json.Unmarshal(body, &resp)
if err != nil {
2022-07-17 18:15:29 -04:00
return post{}, err
2022-07-13 15:07:01 -04:00
}
2022-11-12 12:55:14 -05:00
if len(resp.Data.Children) < 1 {
return post{}, errors.New("bad data from reddit")
}
2023-03-20 11:40:07 -04:00
reSearch := re.FindStringSubmatch(resp.Data.Children[0].Data.Title)
if len(reSearch) == 0 {
2023-10-10 21:01:01 -04:00
return post{}, fmt.Errorf("something strange in data from reddit")
2023-03-20 11:40:07 -04:00
}
numS := reSearch[0]
2022-07-29 16:02:23 -04:00
num, err := strconv.Atoi(numS)
if err != nil || numS == "" {
num = -1
}
2022-07-13 15:07:01 -04:00
return post{
2022-07-29 16:02:23 -04:00
Title: resp.Data.Children[0].Data.Title,
Link: resp.Data.Children[0].Data.URL,
Number: num,
2022-07-17 18:15:29 -04:00
}, nil
2022-07-13 15:07:01 -04:00
}