98 lines
2.2 KiB
Go
98 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"flag"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/turnage/graw"
|
|
"github.com/turnage/graw/reddit"
|
|
)
|
|
|
|
// UA is the user agent for Reddit
|
|
const UA = `NixOS:tulpa.dev/cadey/snoo2nebby:v0.1.0 (by /u/shadowh511)`
|
|
|
|
var (
|
|
agentFile = flag.String("agent-file", "./var/agent.yml", "the path to the bot's reddit agent config")
|
|
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")
|
|
allowNSFW = flag.Bool("allow-nsfw", false, "proxy NSFW posts?")
|
|
)
|
|
|
|
func clampLen(data string) string {
|
|
if len(data) < 1800 {
|
|
return data
|
|
}
|
|
|
|
var sb strings.Builder
|
|
sb.WriteString(data[0:1800])
|
|
sb.WriteString("\n\n[Post truncated for length]")
|
|
|
|
return sb.String()
|
|
}
|
|
|
|
type postReplicatingBot struct {
|
|
whURL string
|
|
bot reddit.Bot
|
|
}
|
|
|
|
func (p *postReplicatingBot) Post(post *reddit.Post) error {
|
|
log.Printf("got new post: by /u/%s: %q %s, NSFW: %v", post.Author, post.URL, post.Title, post.NSFW)
|
|
|
|
if post.NSFW && !*allowNSFW {
|
|
return nil
|
|
}
|
|
|
|
wh := Webhook{
|
|
Embeds: []Embed{
|
|
{
|
|
Title: post.Title,
|
|
URL: post.URL,
|
|
Description: clampLen(post.SelfText),
|
|
Footer: EmbedFooter{
|
|
Text: "by /u/" + post.Author,
|
|
},
|
|
},
|
|
},
|
|
}
|
|
|
|
req := Send(p.whURL, wh)
|
|
req.Header.Set("User-Agent", UA)
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return fmt.Errorf("can't send webhook: %w", err)
|
|
}
|
|
err = Validate(resp)
|
|
if err != nil {
|
|
return fmt.Errorf("can't validate response: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func main() {
|
|
flag.Parse()
|
|
|
|
script, err := reddit.NewBotFromAgentFile(*agentFile, 5*time.Minute)
|
|
|
|
whSlc, err := ioutil.ReadFile(*webhookFile)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
whURL := string(bytes.TrimSpace(whSlc))
|
|
|
|
log.Printf("listening for new posts on /r/%s", *subreddit)
|
|
|
|
if _, wait, err := graw.Run(&postReplicatingBot{whURL, script}, script, graw.Config{Subreddits: []string{*subreddit}}); err != nil {
|
|
log.Fatalf("can't connect to reddit: %v", err)
|
|
} else {
|
|
log.Fatalf("graw run failed: %v", wait())
|
|
}
|
|
}
|