Phase 1, part 3: Reddit

- Sign in with a Reddit web app; access tokens refresh automatically,
  and an app-only token reads rules before sign-in.
- Reddit drafts: a title and text for one subreddit, chosen when
  writing. The subreddit's guidelines and rules go into the prompt, which
  asks for a community member's post that discloses the affiliation and
  avoids marketing language.
- The Inbox shows the subreddit's rules (cached for a day, with Refresh)
  and warns, without blocking, about promotion rules, restricted
  subreddits, link-only subreddits, posting in the same subreddit within
  a week, more than 1 in 10 recent posts linking to the company's sites,
  and new accounts.
- Publishing makes a text post with the source link at the end, or a
  link post where the subreddit takes only links.
- Migration 4 adds the draft's title and subreddit, and the rules cache.
  Publishers now take a Post, which carries the title and subreddit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 13:51:16 -07:00
co-authored by Claude Opus 5.5
parent b0f06058ec
commit 0e34f574b7
27 changed files with 1404 additions and 91 deletions
+297
View File
@@ -0,0 +1,297 @@
// Package reddit talks to Reddit's API: the signed-in user, submitting
// posts, a subreddit's rules, and the account's recent posts (for the
// posting-too-often warnings).
package reddit
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// Hosts. Authenticated calls go to oauth.reddit.com.
const (
apiBase = "https://oauth.reddit.com"
// TitleLimit and BodyLimit are Reddit's limits for a post.
TitleLimit = 300
BodyLimit = 40000
)
// TokenRefresher gets a new access token after a 401.
type TokenRefresher func(ctx context.Context) (string, error)
// Client calls Reddit as one user (or as the app, for reading).
type Client struct {
token string
userAgent string
refresh TokenRefresher
http *http.Client
base string // for tests
}
// New returns a client. Reddit asks every client for a unique User-Agent;
// see UserAgent.
func New(accessToken, userAgent string, refresh TokenRefresher) *Client {
return &Client{token: accessToken, userAgent: userAgent, refresh: refresh,
http: &http.Client{Timeout: 20 * time.Second}, base: apiBase}
}
// UserAgent is the User-Agent Reddit's rules ask for.
func UserAgent(version, username string) string {
ua := "web:supermarket:" + version
if username != "" {
ua += " (by /u/" + username + ")"
}
return ua
}
// ErrUnauthorized means the token was refused even after a refresh.
var ErrUnauthorized = errors.New("Reddit refused the sign-in: connect Reddit again under Settings → Credentials")
func (c *Client) do(ctx context.Context, method, path string, form url.Values, out any) error {
for attempt := 0; ; attempt++ {
var body io.Reader
if form != nil {
body = strings.NewReader(form.Encode())
}
req, err := http.NewRequestWithContext(ctx, method, c.base+path, body)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("User-Agent", c.userAgent)
if form != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
res, err := c.http.Do(req)
if err != nil {
return err
}
raw, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20))
res.Body.Close()
if res.StatusCode == http.StatusUnauthorized && attempt == 0 && c.refresh != nil {
tok, err := c.refresh(ctx)
if err != nil {
return fmt.Errorf("%w (%v)", ErrUnauthorized, err)
}
c.token = tok
continue
}
switch {
case res.StatusCode == http.StatusUnauthorized:
return ErrUnauthorized
case res.StatusCode == http.StatusForbidden:
return fmt.Errorf("Reddit said 403 Forbidden: the subreddit may be private, or the account banned from it")
case res.StatusCode == http.StatusNotFound:
return fmt.Errorf("Reddit said 404: no such subreddit or user")
case res.StatusCode == http.StatusTooManyRequests:
return fmt.Errorf("Reddit is rate-limiting this app; try again in a few minutes")
case res.StatusCode != http.StatusOK:
return fmt.Errorf("reddit HTTP %d: %.300s", res.StatusCode, raw)
}
if out == nil {
return nil
}
return json.Unmarshal(raw, out)
}
}
// Me returns the signed-in user's name.
func (c *Client) Me(ctx context.Context) (string, error) {
var me struct {
Name string `json:"name"`
}
if err := c.do(ctx, http.MethodGet, "/api/v1/me", nil, &me); err != nil {
return "", err
}
if me.Name == "" {
return "", errors.New("Reddit didn't say who is signed in")
}
return me.Name, nil
}
// Post is a submission.
type Post struct {
Subreddit string
Title string
Text string // a text ("self") post's body
URL string // set for a link post; then Text is ignored
}
// Submit posts to a subreddit and returns the post's URL.
func (c *Client) Submit(ctx context.Context, p Post) (string, error) {
form := url.Values{
"api_type": {"json"},
"sr": {p.Subreddit},
"title": {p.Title},
"resubmit": {"true"},
"sendreplies": {"true"},
}
if p.URL != "" {
form.Set("kind", "link")
form.Set("url", p.URL)
} else {
form.Set("kind", "self")
form.Set("text", p.Text)
}
var out struct {
JSON struct {
Errors [][]any `json:"errors"`
Data struct {
URL string `json:"url"`
} `json:"data"`
} `json:"json"`
}
if err := c.do(ctx, http.MethodPost, "/api/submit", form, &out); err != nil {
return "", err
}
if len(out.JSON.Errors) > 0 {
var msgs []string
for _, e := range out.JSON.Errors {
// Each error is [code, message, field].
if len(e) > 1 {
msgs = append(msgs, fmt.Sprint(e[1]))
} else if len(e) > 0 {
msgs = append(msgs, fmt.Sprint(e[0]))
}
}
return "", fmt.Errorf("Reddit refused the post: %s", strings.Join(msgs, "; "))
}
if out.JSON.Data.URL == "" {
return "", errors.New("Reddit accepted the post but didn't return its address")
}
return out.JSON.Data.URL, nil
}
// Rule is one of a subreddit's rules.
type Rule struct {
Name string `json:"name"`
Description string `json:"description"`
Kind string `json:"kind"` // link, comment, all
}
// Subreddit is what the app shows and tells the model about a subreddit.
type Subreddit struct {
Name string `json:"name"`
Title string `json:"title"`
Description string `json:"description"` // public description
SubmitText string `json:"submit_text"` // posting guidelines shown when posting
SubmissionType string `json:"submission_type"` // any, link, self
Type string `json:"type"` // public, restricted, private
Over18 bool `json:"over18"`
Subscribers int `json:"subscribers"`
Rules []Rule `json:"rules"`
FetchedAt time.Time `json:"fetched_at"`
}
// AllowsText reports whether text posts are allowed.
func (s *Subreddit) AllowsText() bool { return s.SubmissionType != "link" }
// AllowsLinks reports whether link posts are allowed.
func (s *Subreddit) AllowsLinks() bool { return s.SubmissionType != "self" }
// SubredditInfo fetches a subreddit's description, guidelines and rules.
func (c *Client) SubredditInfo(ctx context.Context, name string) (*Subreddit, error) {
name = CleanName(name)
var about struct {
Data struct {
DisplayName string `json:"display_name"`
Title string `json:"title"`
PublicDescription string `json:"public_description"`
SubmitText string `json:"submit_text"`
SubmissionType string `json:"submission_type"`
SubredditType string `json:"subreddit_type"`
Over18 bool `json:"over18"`
Subscribers int `json:"subscribers"`
} `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/r/"+url.PathEscape(name)+"/about", nil, &about); err != nil {
return nil, err
}
var rules struct {
Rules []struct {
ShortName string `json:"short_name"`
Description string `json:"description"`
Kind string `json:"kind"`
} `json:"rules"`
}
if err := c.do(ctx, http.MethodGet, "/r/"+url.PathEscape(name)+"/about/rules", nil, &rules); err != nil {
return nil, err
}
d := about.Data
s := &Subreddit{Name: firstNonEmpty(d.DisplayName, name), Title: d.Title, Description: d.PublicDescription,
SubmitText: d.SubmitText, SubmissionType: firstNonEmpty(d.SubmissionType, "any"), Type: d.SubredditType,
Over18: d.Over18, Subscribers: d.Subscribers, FetchedAt: time.Now().UTC()}
for _, r := range rules.Rules {
s.Rules = append(s.Rules, Rule{Name: r.ShortName, Description: r.Description, Kind: r.Kind})
}
return s, nil
}
// Submission is one of the account's past posts.
type Submission struct {
Subreddit string
Title string
URL string // the link, for link posts
Text string
IsSelf bool
Created time.Time
}
// Submitted returns the user's recent posts, newest first (up to 100).
func (c *Client) Submitted(ctx context.Context, username string) ([]Submission, error) {
var out struct {
Data struct {
Children []struct {
Data struct {
Subreddit string `json:"subreddit"`
Title string `json:"title"`
URL string `json:"url"`
Selftext string `json:"selftext"`
IsSelf bool `json:"is_self"`
CreatedUTC float64 `json:"created_utc"`
} `json:"data"`
} `json:"children"`
} `json:"data"`
}
path := "/user/" + url.PathEscape(username) + "/submitted?limit=100&sort=new&raw_json=1"
if err := c.do(ctx, http.MethodGet, path, nil, &out); err != nil {
return nil, err
}
var subs []Submission
for _, ch := range out.Data.Children {
d := ch.Data
subs = append(subs, Submission{Subreddit: d.Subreddit, Title: d.Title, URL: d.URL, Text: d.Selftext,
IsSelf: d.IsSelf, Created: time.Unix(int64(d.CreatedUTC), 0).UTC()})
}
return subs, nil
}
// CleanName turns "r/selfhosted", "/r/selfhosted/" or a subreddit URL into
// "selfhosted".
func CleanName(s string) string {
s = strings.TrimSpace(s)
if i := strings.Index(s, "/r/"); i >= 0 {
s = s[i+3:]
}
s = strings.TrimPrefix(s, "r/")
if i := strings.IndexAny(s, "/?#"); i >= 0 {
s = s[:i]
}
return s
}
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if v != "" {
return v
}
}
return ""
}
+85
View File
@@ -0,0 +1,85 @@
package reddit
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestClient(t *testing.T) {
var submitted string
refreshed := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-Agent") != "web:supermarket:test (by /u/pat)" {
t.Errorf("User-Agent = %q", r.Header.Get("User-Agent"))
}
if r.Header.Get("Authorization") == "Bearer old" {
w.WriteHeader(http.StatusUnauthorized)
return
}
switch r.URL.Path {
case "/api/v1/me":
w.Write([]byte(`{"name":"pat"}`))
case "/api/submit":
r.ParseForm()
submitted = r.PostForm.Encode()
if r.PostForm.Get("sr") == "strict" {
w.Write([]byte(`{"json":{"errors":[["SUBREDDIT_NOTALLOWED","you aren't allowed to post there.","sr"]]}}`))
return
}
w.Write([]byte(`{"json":{"errors":[],"data":{"url":"https://www.reddit.com/r/selfhosted/comments/abc/hi/"}}}`))
case "/r/selfhosted/about":
w.Write([]byte(`{"data":{"display_name":"selfhosted","public_description":"Self-hosting","submit_text":"No spam.","submission_type":"self","subreddit_type":"public","subscribers":500000}}`))
case "/r/selfhosted/about/rules":
w.Write([]byte(`{"rules":[{"short_name":"No self-promotion","description":"Limit it to 10%.","kind":"link"}]}`))
case "/user/pat/submitted":
w.Write([]byte(`{"data":{"children":[{"data":{"subreddit":"selfhosted","title":"T","url":"https://acme.example/x","is_self":false,"created_utc":1794000000}}]}}`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
c := New("old", UserAgent("test", "pat"), func(context.Context) (string, error) {
refreshed++
return "new", nil
})
c.base = srv.URL
ctx := context.Background()
if name, err := c.Me(ctx); err != nil || name != "pat" || refreshed != 1 {
t.Fatalf("Me = %q, %v (refreshed %d)", name, err, refreshed)
}
u, err := c.Submit(ctx, Post{Subreddit: "selfhosted", Title: "Hi", Text: "Body"})
if err != nil || !strings.Contains(u, "/comments/abc/") || !strings.Contains(submitted, "kind=self") || !strings.Contains(submitted, "text=Body") {
t.Errorf("Submit = %q, %v; sent %s", u, err, submitted)
}
if _, err := c.Submit(ctx, Post{Subreddit: "selfhosted", Title: "Hi", URL: "https://acme.example"}); err != nil || !strings.Contains(submitted, "kind=link") {
t.Errorf("link post sent %s (%v)", submitted, err)
}
if _, err := c.Submit(ctx, Post{Subreddit: "strict", Title: "Hi", Text: "x"}); err == nil || !strings.Contains(err.Error(), "aren't allowed") {
t.Errorf("refused submit: %v", err)
}
s, err := c.SubredditInfo(ctx, "/r/selfhosted/")
if err != nil || s.SubmitText != "No spam." || len(s.Rules) != 1 || s.Rules[0].Name != "No self-promotion" || s.AllowsLinks() || !s.AllowsText() {
t.Errorf("SubredditInfo = %+v, %v", s, err)
}
subs, err := c.Submitted(ctx, "pat")
if err != nil || len(subs) != 1 || subs[0].Subreddit != "selfhosted" || subs[0].Created.Year() != 2026 {
t.Errorf("Submitted = %+v, %v", subs, err)
}
if _, err := c.SubredditInfo(ctx, "nope"); err == nil {
t.Error("expected 404")
}
}
func TestCleanName(t *testing.T) {
for in, want := range map[string]string{"selfhosted": "selfhosted", "r/selfhosted": "selfhosted", "/r/selfhosted/": "selfhosted",
"https://www.reddit.com/r/homelab/top?t=week": "homelab", " r/Go ": "Go"} {
if got := CleanName(in); got != want {
t.Errorf("CleanName(%q) = %q, want %q", in, got, want)
}
}
}