This repository has been archived on 2022-03-09. You can view files and clone it, but cannot push or open issues or pull requests.
snoo2nebby/main.go

84 lines
1.7 KiB
Go

package main
import (
"bytes"
"flag"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/turnage/graw/reddit"
"github.com/turnage/graw/streams"
)
// UA is the user agent for Reddit
const UA = `NixOS:tulpa.dev/cadey/snoo2nebby:v0.1.0 (by /u/shadowh511)`
var (
webhookFile = flag.String("webhook-file", "./var/webhook.txt", "where the Discord webhook file is located")
subreddit = flag.String("subreddit", "tulpas", "the subreddit to monitor")
pokeFreq = flag.Duration("poke-frequency", 5*time.Minute, "how often the bot should poke the feed")
)
func main() {
flag.Parse()
script, err := reddit.NewScript(UA, *pokeFreq)
if err != nil {
log.Fatal(err)
}
whSlc, err := os.ReadFile(*webhookFile)
if err != nil {
log.Fatal(err)
}
whURL := string(bytes.TrimSpace(whSlc))
kill := make(chan bool)
errs := make(chan error)
stream, err := streams.Subreddits(script, kill, errs, *subreddit)
if err != nil {
log.Fatal(err)
}
go func(errs chan error) {
for err := range errs {
log.Printf("%v", err)
}
}(errs)
log.Printf("listening for new posts on /r/%s", *subreddit)
for post := range stream {
log.Printf("got new post: by /u/%s: %q %s", post.Author, post.URL, post.Title)
wh := Webhook{
Embeds: []Embed{
{
Title: post.Title,
URL: post.URL,
Description: post.SelfText,
Footer: EmbedFooter{
Text: "by /u/" + post.Author,
},
},
},
}
req := Send(whURL, wh)
req.Header.Set("User-Agent", UA)
resp, err := http.DefaultClient.Do(req)
if err != nil {
errs <- fmt.Errorf("can't send webhook: %w", err)
continue
}
err = Validate(resp)
if err != nil {
errs <- fmt.Errorf("can't validate response: %w", err)
continue
}
}
}