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:
@@ -83,8 +83,12 @@ type fakePub struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakePub) Publish(_ context.Context, text, src string) (string, error) {
|
||||
f.calls = append(f.calls, text+"|"+src)
|
||||
func (f *fakePub) Publish(_ context.Context, p Post) (string, error) {
|
||||
call := p.Text + "|" + p.SourceURL
|
||||
if p.Target != "" {
|
||||
call = "r/" + p.Target + "|" + p.Title + "|" + call
|
||||
}
|
||||
f.calls = append(f.calls, call)
|
||||
if f.err != nil {
|
||||
return "", f.err
|
||||
}
|
||||
|
||||
@@ -19,8 +19,12 @@ import (
|
||||
const (
|
||||
ChannelX = "x"
|
||||
ChannelLinkedIn = "linkedin"
|
||||
ChannelReddit = "reddit"
|
||||
)
|
||||
|
||||
// RedditTitleLimit is the longest title Reddit takes.
|
||||
const RedditTitleLimit = 300
|
||||
|
||||
// Channel describes where drafts are published.
|
||||
type Channel struct {
|
||||
ID string
|
||||
@@ -32,6 +36,7 @@ type Channel struct {
|
||||
var Channels = []Channel{
|
||||
{ChannelX, "X", 280},
|
||||
{ChannelLinkedIn, "LinkedIn", 3000},
|
||||
{ChannelReddit, "Reddit", 40000},
|
||||
}
|
||||
|
||||
// ChannelByID returns the channel, or false.
|
||||
@@ -61,6 +66,8 @@ type Draft struct {
|
||||
InventoryName string
|
||||
Kind string // the entry's relationship
|
||||
Channel string
|
||||
Title string // Reddit only
|
||||
Target string // Reddit: the subreddit, without r/
|
||||
Content string
|
||||
SourceURL string // added when publishing: appended on X, a link preview on LinkedIn
|
||||
ItemIDs []string
|
||||
@@ -94,7 +101,36 @@ func (d *Draft) Limit() int {
|
||||
}
|
||||
|
||||
// TooLong reports whether the draft can't be published as it is.
|
||||
func (d *Draft) TooLong() bool { return d.Length() > d.Limit() }
|
||||
func (d *Draft) TooLong() bool {
|
||||
return d.Length() > d.Limit() || utf8.RuneCountInString(d.Title) > RedditTitleLimit
|
||||
}
|
||||
|
||||
// Problem says what stops the draft from being published, or "".
|
||||
func (d *Draft) Problem() string {
|
||||
switch {
|
||||
case d.Channel == ChannelReddit && strings.TrimSpace(d.Title) == "":
|
||||
return "the Reddit post needs a title"
|
||||
case d.Channel == ChannelReddit && d.Target == "":
|
||||
return "the Reddit post has no subreddit"
|
||||
case utf8.RuneCountInString(d.Title) > RedditTitleLimit:
|
||||
return fmt.Sprintf("the title is %d characters; Reddit allows %d", utf8.RuneCountInString(d.Title), RedditTitleLimit)
|
||||
case d.Length() > d.Limit():
|
||||
withLink := ""
|
||||
if d.Channel == ChannelX && d.SourceURL != "" {
|
||||
withLink = " including the link"
|
||||
}
|
||||
return fmt.Sprintf("the post is %d characters%s; %s allows %d", d.Length(), withLink, d.ChannelName(), d.Limit())
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Where is the channel plus, for Reddit, the subreddit: "Reddit r/golang".
|
||||
func (d *Draft) Where() string {
|
||||
if d.Target != "" {
|
||||
return d.ChannelName() + " r/" + d.Target
|
||||
}
|
||||
return d.ChannelName()
|
||||
}
|
||||
|
||||
// ChannelName is the channel's display name.
|
||||
func (d *Draft) ChannelName() string {
|
||||
@@ -131,9 +167,9 @@ func CreateDrafts(d *db.DB, drafts []Draft) (string, error) {
|
||||
return "", fmt.Errorf("unknown channel %q", dr.Channel)
|
||||
}
|
||||
ids, _ := json.Marshal(nonNil(dr.ItemIDs))
|
||||
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, content, source_url, item_ids)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel,
|
||||
strings.TrimSpace(dr.Content), dr.SourceURL, string(ids)); err != nil {
|
||||
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel,
|
||||
strings.TrimSpace(dr.Title), dr.Target, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids)); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, id := range dr.ItemIDs {
|
||||
@@ -157,7 +193,7 @@ func nonNil(s []string) []string {
|
||||
}
|
||||
|
||||
const draftColumns = `id, batch, inventory_name, kind, channel, content, source_url, item_ids, status, error,
|
||||
post_url, created_at, updated_at, COALESCE(published_at, ''), COALESCE(publish_at, '')`
|
||||
post_url, created_at, updated_at, COALESCE(published_at, ''), COALESCE(publish_at, ''), title, target`
|
||||
|
||||
func scanDrafts(rows *sql.Rows) ([]Draft, error) {
|
||||
defer rows.Close()
|
||||
@@ -166,7 +202,7 @@ func scanDrafts(rows *sql.Rows) ([]Draft, error) {
|
||||
var dr Draft
|
||||
var ids, created, updated, published, publishAt string
|
||||
if err := rows.Scan(&dr.ID, &dr.Batch, &dr.InventoryName, &dr.Kind, &dr.Channel, &dr.Content,
|
||||
&dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published, &publishAt); err != nil {
|
||||
&dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published, &publishAt, &dr.Title, &dr.Target); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = json.Unmarshal([]byte(ids), &dr.ItemIDs)
|
||||
@@ -320,3 +356,14 @@ func FailScheduled(d *db.DB, id int64, reason string) error {
|
||||
StatusFailed, reason, formatTime(time.Now()), id, StatusScheduled)
|
||||
return oneRow(res, err)
|
||||
}
|
||||
|
||||
// UpdateTitle saves an edited Reddit title.
|
||||
func UpdateTitle(d *db.DB, id int64, title string) error {
|
||||
title = strings.Join(strings.Fields(title), " ")
|
||||
if title == "" {
|
||||
return errors.New("the title is empty")
|
||||
}
|
||||
res, err := d.Exec(`UPDATE drafts SET title = ?, updated_at = ? WHERE id = ? AND channel = ? AND status IN (?, ?)`,
|
||||
title, formatTime(time.Now()), id, ChannelReddit, StatusDraft, StatusFailed)
|
||||
return oneRow(res, err)
|
||||
}
|
||||
|
||||
@@ -2,11 +2,13 @@ package content
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"supermarket/internal/ai"
|
||||
"supermarket/internal/api/reddit"
|
||||
"supermarket/internal/api/twitter"
|
||||
"supermarket/internal/inventory"
|
||||
"supermarket/internal/profile"
|
||||
@@ -18,6 +20,10 @@ type Request struct {
|
||||
Entry *inventory.Entry
|
||||
Items []Item
|
||||
Channels []string // channel IDs, in Channels order
|
||||
// Reddit: the subreddit to write for, and what's known about it (nil
|
||||
// if its rules couldn't be read).
|
||||
Subreddit string
|
||||
SubredditInfo *reddit.Subreddit
|
||||
}
|
||||
|
||||
// SourceURL is the link the drafts carry: the first item's.
|
||||
@@ -55,15 +61,30 @@ func Generate(ctx context.Context, client ai.Client, req Request) ([]Draft, erro
|
||||
if _, ok := ChannelByID(ch); !ok {
|
||||
return nil, fmt.Errorf("unknown channel %q", ch)
|
||||
}
|
||||
if ch == ChannelReddit && req.Subreddit == "" {
|
||||
return nil, errors.New("choose a subreddit to write the Reddit post for")
|
||||
}
|
||||
}
|
||||
src := req.SourceURL()
|
||||
|
||||
props := map[string]any{}
|
||||
for _, ch := range req.Channels {
|
||||
c, _ := ChannelByID(ch)
|
||||
if ch == ChannelReddit {
|
||||
props[ch] = map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"title": map[string]any{"type": "string", "description": "The post's title"},
|
||||
"body": map[string]any{"type": "string", "description": "The post's text"},
|
||||
},
|
||||
"required": []string{"title", "body"},
|
||||
"additionalProperties": false,
|
||||
}
|
||||
continue
|
||||
}
|
||||
props[ch] = map[string]any{"type": "string", "description": "The " + c.Name + " post"}
|
||||
}
|
||||
var out map[string]string
|
||||
var out map[string]json.RawMessage
|
||||
err := ai.GenerateJSON(ctx, client, ai.Request{
|
||||
Task: ai.TaskContent,
|
||||
System: systemPrompt(req.Profile),
|
||||
@@ -86,7 +107,24 @@ func Generate(ctx context.Context, client ai.Client, req Request) ([]Draft, erro
|
||||
}
|
||||
var drafts []Draft
|
||||
for _, ch := range req.Channels {
|
||||
text := strings.TrimSpace(out[ch])
|
||||
if ch == ChannelReddit {
|
||||
var rp struct{ Title, Body string }
|
||||
_ = json.Unmarshal(out[ch], &rp)
|
||||
if strings.TrimSpace(rp.Body) == "" || strings.TrimSpace(rp.Title) == "" {
|
||||
return nil, errors.New("the model wrote no Reddit title or text")
|
||||
}
|
||||
title := strings.Join(strings.Fields(rp.Title), " ")
|
||||
if r := []rune(title); len(r) > RedditTitleLimit {
|
||||
title = string(r[:RedditTitleLimit-1]) + "…"
|
||||
}
|
||||
drafts = append(drafts, Draft{InventoryName: req.Entry.Name, Kind: req.Entry.Relationship, Channel: ch,
|
||||
Title: title, Target: reddit.CleanName(req.Subreddit), Content: strings.TrimSpace(rp.Body),
|
||||
SourceURL: src, ItemIDs: ids, Status: StatusDraft})
|
||||
continue
|
||||
}
|
||||
var text string
|
||||
_ = json.Unmarshal(out[ch], &text)
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
return nil, fmt.Errorf("the model wrote nothing for %s", ch)
|
||||
}
|
||||
@@ -227,6 +265,8 @@ func userPrompt(req Request, src string) string {
|
||||
case ChannelLinkedIn:
|
||||
fmt.Fprintf(&b, "- linkedin: a LinkedIn post, usually 400 to 1,300 characters and never more than %d. "+
|
||||
"A strong first line, short paragraphs, then up to 3 hashtags on the last line. Plain text, no markdown.\n", limit)
|
||||
case ChannelReddit:
|
||||
b.WriteString(redditInstructions(req))
|
||||
}
|
||||
}
|
||||
if src != "" {
|
||||
@@ -238,3 +278,40 @@ func userPrompt(req Request, src string) string {
|
||||
func oneLine(s string) string {
|
||||
return strings.Join(strings.Fields(s), " ")
|
||||
}
|
||||
|
||||
// redditInstructions asks for a post that a community would welcome: Reddit
|
||||
// punishes marketing, so the rules are stricter than for other channels.
|
||||
func redditInstructions(req Request) string {
|
||||
var b strings.Builder
|
||||
sub := reddit.CleanName(req.Subreddit)
|
||||
fmt.Fprintf(&b, "- reddit: an object with a title (at most %d characters) and a body, for r/%s. "+
|
||||
"Write as a member of the community who works at %s, and say so plainly in the body (\"I work at %s\"). "+
|
||||
"Lead with what's useful or interesting to this community, not with the company. No hashtags, no emoji, no marketing language, "+
|
||||
"no calls to action. Usually 80 to 250 words, in Reddit's markdown. The title must read like a normal post title, not a headline ad. "+
|
||||
"Follow the subreddit's rules below; if they forbid promotion, write a genuine discussion post that doesn't promote anything.\n",
|
||||
RedditTitleLimit, sub, req.Profile.Name, req.Profile.Name)
|
||||
if info := req.SubredditInfo; info != nil {
|
||||
b.WriteString("<subreddit>\n")
|
||||
if info.Description != "" {
|
||||
fmt.Fprintf(&b, "About r/%s: %s\n", sub, oneLine(info.Description))
|
||||
}
|
||||
if info.SubmitText != "" {
|
||||
fmt.Fprintf(&b, "Posting guidelines: %s\n", oneLine(truncateRunes(info.SubmitText, 1500)))
|
||||
}
|
||||
for i, r := range info.Rules {
|
||||
if r.Kind == "comment" {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&b, "Rule %d: %s. %s\n", i+1, r.Name, oneLine(truncateRunes(r.Description, 400)))
|
||||
}
|
||||
b.WriteString("</subreddit>\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func truncateRunes(s string, n int) string {
|
||||
if r := []rune(s); len(r) > n {
|
||||
return string(r[:n]) + "…"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -10,9 +10,17 @@ import (
|
||||
"supermarket/internal/utm"
|
||||
)
|
||||
|
||||
// Post is what a publisher sends.
|
||||
type Post struct {
|
||||
Text string
|
||||
SourceURL string // tagged, if it's the company's
|
||||
Title string // Reddit
|
||||
Target string // Reddit: the subreddit
|
||||
}
|
||||
|
||||
// Publisher posts to one channel and returns the post's URL.
|
||||
type Publisher interface {
|
||||
Publish(ctx context.Context, text, sourceURL string) (string, error)
|
||||
Publish(ctx context.Context, p Post) (string, error)
|
||||
}
|
||||
|
||||
// Publishers are the channels that can post now, by channel ID.
|
||||
@@ -39,13 +47,8 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, i
|
||||
if pub == nil {
|
||||
return dr, fmt.Errorf("%s isn't connected: sign in under Settings → Credentials", dr.ChannelName())
|
||||
}
|
||||
if dr.TooLong() {
|
||||
withLink := ""
|
||||
if dr.Channel == ChannelX && dr.SourceURL != "" {
|
||||
withLink = " including the link"
|
||||
}
|
||||
return dr, fmt.Errorf("the post is %d characters%s; %s allows %d. Shorten it first",
|
||||
dr.Length(), withLink, dr.ChannelName(), dr.Limit())
|
||||
if problem := dr.Problem(); problem != "" {
|
||||
return dr, fmt.Errorf("%s. Fix it first", problem)
|
||||
}
|
||||
|
||||
res, err := d.Exec(`UPDATE drafts SET status = ?, error = '', updated_at = ? WHERE id = ? AND status IN (?, ?, ?)`,
|
||||
@@ -62,7 +65,7 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, i
|
||||
p := dr.UTM()
|
||||
text, src = tags.Text(text, p), tags.URL(src, p)
|
||||
}
|
||||
postURL, pubErr := pub.Publish(ctx, text, src)
|
||||
postURL, pubErr := pub.Publish(ctx, Post{Text: text, SourceURL: src, Title: dr.Title, Target: dr.Target})
|
||||
now := formatTime(time.Now())
|
||||
if pubErr != nil {
|
||||
if _, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ? WHERE id = ?`,
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package content
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/api/reddit"
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// SubredditMaxAge is how long a subreddit's cached rules are used before
|
||||
// they're fetched again.
|
||||
const SubredditMaxAge = 24 * time.Hour
|
||||
|
||||
// GetSubreddit returns the cached subreddit, or nil.
|
||||
func GetSubreddit(d *db.DB, name string) (*reddit.Subreddit, error) {
|
||||
var raw string
|
||||
err := d.QueryRow(`SELECT data FROM subreddits WHERE name = ?`, reddit.CleanName(name)).Scan(&raw)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var s reddit.Subreddit
|
||||
if err := json.Unmarshal([]byte(raw), &s); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
// SaveSubreddit caches a subreddit's rules.
|
||||
func SaveSubreddit(d *db.DB, s *reddit.Subreddit) error {
|
||||
raw, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = d.Exec(`INSERT INTO subreddits (name, data, fetched_at) VALUES (?, ?, ?)
|
||||
ON CONFLICT (name) DO UPDATE SET data = excluded.data, fetched_at = excluded.fetched_at`,
|
||||
s.Name, string(raw), formatTime(s.FetchedAt))
|
||||
return err
|
||||
}
|
||||
|
||||
// Reddit's self-promotion guideline: at most one post in ten about your own
|
||||
// work. Posting to the same subreddit more than about weekly reads as spam.
|
||||
const (
|
||||
ownShareLimit = 0.10
|
||||
sameSubWindow = 7 * 24 * time.Hour
|
||||
historyWindow = 30 * 24 * time.Hour
|
||||
)
|
||||
|
||||
var promoRule = regexp.MustCompile(`(?i)promot|advertis|spam|marketing|self-?post|affiliat|commercial|vendor|blogspam`)
|
||||
|
||||
// RedditCheck is what the warnings are worked out from.
|
||||
type RedditCheck struct {
|
||||
Target string
|
||||
HasLink bool // the draft carries a link
|
||||
OwnLink bool // to the company's own site
|
||||
Info *reddit.Subreddit // nil if the rules couldn't be read
|
||||
History []reddit.Submission // the account's recent posts; nil if unknown
|
||||
Own func(url string) bool
|
||||
Now time.Time
|
||||
}
|
||||
|
||||
// RedditWarnings lists reasons to think twice before posting. They never
|
||||
// block publishing: the user decides.
|
||||
func RedditWarnings(c RedditCheck) []string {
|
||||
var w []string
|
||||
sub := "r/" + c.Target
|
||||
if c.Info == nil {
|
||||
w = append(w, "Couldn't read "+sub+"'s rules: check them on Reddit before posting.")
|
||||
} else {
|
||||
if c.Info.Type == "restricted" || c.Info.Type == "private" {
|
||||
w = append(w, fmt.Sprintf("%s is %s: only approved users can post.", sub, c.Info.Type))
|
||||
}
|
||||
if !c.Info.AllowsText() && !c.HasLink {
|
||||
w = append(w, sub+" only takes link posts, and this draft has no link.")
|
||||
} else if !c.Info.AllowsText() {
|
||||
w = append(w, sub+" only takes link posts: it will be posted as the title and the link, without the text.")
|
||||
}
|
||||
for _, r := range c.Info.Rules {
|
||||
if promoRule.MatchString(r.Name + " " + r.Description) {
|
||||
w = append(w, fmt.Sprintf("%s has a rule about this: “%s”.", sub, r.Name))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if c.History == nil {
|
||||
return w
|
||||
}
|
||||
if len(c.History) == 0 {
|
||||
w = append(w, "This account hasn't posted before. Communities often remove a new account's first posts, especially promotional ones: take part in discussions first.")
|
||||
return w
|
||||
}
|
||||
var inSub []time.Time
|
||||
recent, own := 0, 0
|
||||
for _, s := range c.History {
|
||||
age := c.Now.Sub(s.Created)
|
||||
if strings.EqualFold(s.Subreddit, c.Target) && age < sameSubWindow {
|
||||
inSub = append(inSub, s.Created)
|
||||
}
|
||||
if age < historyWindow {
|
||||
recent++
|
||||
if c.Own != nil && (c.Own(s.URL) || containsOwnLink(s.Text, c.Own)) {
|
||||
own++
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(inSub) > 0 {
|
||||
w = append(w, fmt.Sprintf("You posted in %s %d time%s in the past week, last on %s. Most communities expect less.",
|
||||
sub, len(inSub), plural(len(inSub)), inSub[0].Local().Format("2 Jan")))
|
||||
}
|
||||
// Count this post as one more own link, if it has one.
|
||||
if c.OwnLink {
|
||||
share := float64(own+1) / float64(recent+1)
|
||||
if share > ownShareLimit && own+1 > 1 {
|
||||
w = append(w, fmt.Sprintf("With this one, %d of your %d posts in the past 30 days link to your own sites. Reddit's guideline is at most 1 in 10.",
|
||||
own+1, recent+1))
|
||||
}
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
var urlPattern = regexp.MustCompile(`https?://[^\s)\]>"]+`)
|
||||
|
||||
func containsOwnLink(text string, own func(string) bool) bool {
|
||||
for _, u := range urlPattern.FindAllString(text, -1) {
|
||||
if own(u) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func plural(n int) string {
|
||||
if n == 1 {
|
||||
return ""
|
||||
}
|
||||
return "s"
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package content
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/api/reddit"
|
||||
"supermarket/internal/inventory"
|
||||
"supermarket/internal/utm"
|
||||
)
|
||||
|
||||
func TestGenerateReddit(t *testing.T) {
|
||||
entry := &inventory.Entry{Name: "Jitsi", Relationship: inventory.Partner}
|
||||
items := []Item{{ContentItem: item("1", "Jitsi", time.Now())}}
|
||||
info := &reddit.Subreddit{Name: "selfhosted", Description: "Self-hosting", SubmitText: "Flair your post.",
|
||||
Rules: []reddit.Rule{{Name: "No spam", Description: "10% rule", Kind: "link"}, {Name: "Be civil", Kind: "comment"}}}
|
||||
f := &fakeAI{replies: []string{`{"x": "Short", "reddit": {"title": " Jitsi 3 is out ", "body": "I work at Acme. Details."}}`}}
|
||||
drafts, err := Generate(context.Background(), f, Request{Profile: testProfile(), Entry: entry, Items: items,
|
||||
Channels: []string{ChannelX, ChannelReddit}, Subreddit: "r/selfhosted", SubredditInfo: info})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := drafts[1]
|
||||
if r.Channel != ChannelReddit || r.Title != "Jitsi 3 is out" || r.Target != "selfhosted" || r.Content != "I work at Acme. Details." {
|
||||
t.Fatalf("reddit draft = %+v", r)
|
||||
}
|
||||
prompt := f.reqs[0].Prompt
|
||||
for _, want := range []string{"r/selfhosted", "I work at Acme", "No hashtags", "Flair your post.", "Rule 1: No spam"} {
|
||||
if !strings.Contains(prompt, want) {
|
||||
t.Errorf("prompt lacks %q", want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(prompt, "Be civil") {
|
||||
t.Error("comment-only rules needn't go in the prompt")
|
||||
}
|
||||
props := f.reqs[0].Schema["properties"].(map[string]any)
|
||||
if props["reddit"].(map[string]any)["type"] != "object" {
|
||||
t.Errorf("reddit schema = %v", props["reddit"])
|
||||
}
|
||||
// A Reddit draft needs a subreddit.
|
||||
if _, err := Generate(context.Background(), f, Request{Profile: testProfile(), Entry: entry, Items: items, Channels: []string{ChannelReddit}}); err == nil {
|
||||
t.Error("expected an error without a subreddit")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedditDraftsAndCache(t *testing.T) {
|
||||
d := openDB(t)
|
||||
_, err := CreateDrafts(d, []Draft{{Channel: ChannelReddit, Title: "Hi", Target: "selfhosted", Content: "Body", SourceURL: "https://acme.example/a"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ds, _ := ListDrafts(d, 1, StatusDraft)
|
||||
dr := ds[0]
|
||||
if dr.Title != "Hi" || dr.Target != "selfhosted" || dr.Where() != "Reddit r/selfhosted" || dr.Problem() != "" {
|
||||
t.Fatalf("draft = %+v (%s)", dr, dr.Problem())
|
||||
}
|
||||
if err := UpdateTitle(d, dr.ID, " New title "); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := UpdateTitle(d, dr.ID, " "); err == nil {
|
||||
t.Error("empty title accepted")
|
||||
}
|
||||
got, _ := GetDraft(d, dr.ID)
|
||||
if got.Title != "New title" {
|
||||
t.Errorf("title = %q", got.Title)
|
||||
}
|
||||
got.Title = strings.Repeat("t", 301)
|
||||
if !strings.Contains(got.Problem(), "title is 301") {
|
||||
t.Errorf("problem = %q", got.Problem())
|
||||
}
|
||||
|
||||
pub := &fakePub{}
|
||||
if _, err := Publish(context.Background(), d, Publishers{ChannelReddit: pub}, utm.NewTagger([]string{"acme.example"}), dr.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(pub.calls[0], "r/selfhosted|New title|Body|https://acme.example/a?utm_") ||
|
||||
!strings.Contains(pub.calls[0], "utm_source=reddit") {
|
||||
t.Errorf("published %q", pub.calls[0])
|
||||
}
|
||||
|
||||
if s, err := GetSubreddit(d, "selfhosted"); s != nil || err != nil {
|
||||
t.Fatalf("empty cache: %v %v", s, err)
|
||||
}
|
||||
at := time.Now().UTC().Truncate(time.Second)
|
||||
if err := SaveSubreddit(d, &reddit.Subreddit{Name: "selfhosted", SubmissionType: "self", Rules: []reddit.Rule{{Name: "R"}}, FetchedAt: at}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := GetSubreddit(d, "r/SelfHosted")
|
||||
if err != nil || s == nil || len(s.Rules) != 1 || !s.FetchedAt.Equal(at) || s.AllowsLinks() {
|
||||
t.Errorf("cached = %+v, %v", s, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedditWarnings(t *testing.T) {
|
||||
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
|
||||
own := utm.NewTagger([]string{"acme.example"}).Own
|
||||
info := &reddit.Subreddit{Name: "selfhosted", SubmissionType: "link", Type: "restricted",
|
||||
Rules: []reddit.Rule{{Name: "No self-promotion"}, {Name: "Be nice"}}}
|
||||
|
||||
has := func(ws []string, sub string) bool {
|
||||
for _, w := range ws {
|
||||
if strings.Contains(w, sub) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
w := RedditWarnings(RedditCheck{Target: "selfhosted", Info: info, Now: now})
|
||||
if !has(w, "restricted") || !has(w, "has no link") || !has(w, "“No self-promotion”") || has(w, "Be nice") || has(w, "past week") {
|
||||
t.Errorf("rules warnings = %q", w)
|
||||
}
|
||||
if w := RedditWarnings(RedditCheck{Target: "x", Now: now}); !has(w, "Couldn't read r/x's rules") {
|
||||
t.Errorf("no info = %q", w)
|
||||
}
|
||||
if w := RedditWarnings(RedditCheck{Target: "x", Info: &reddit.Subreddit{}, History: []reddit.Submission{}, Now: now}); !has(w, "hasn't posted before") {
|
||||
t.Errorf("new account = %q", w)
|
||||
}
|
||||
|
||||
history := []reddit.Submission{
|
||||
{Subreddit: "SelfHosted", URL: "https://acme.example/1", Created: now.Add(-2 * 24 * time.Hour)},
|
||||
{Subreddit: "homelab", Text: "see https://acme.example/2)", IsSelf: true, Created: now.Add(-10 * 24 * time.Hour)},
|
||||
{Subreddit: "golang", Created: now.Add(-20 * 24 * time.Hour)},
|
||||
{Subreddit: "selfhosted", URL: "https://acme.example/old", Created: now.Add(-60 * 24 * time.Hour)},
|
||||
}
|
||||
w = RedditWarnings(RedditCheck{Target: "selfhosted", Info: &reddit.Subreddit{}, History: history, Own: own, OwnLink: true, HasLink: true, Now: now})
|
||||
if !has(w, "posted in r/selfhosted 1 time in the past week") || !has(w, "3 of your 4 posts") {
|
||||
t.Errorf("history warnings = %q", w)
|
||||
}
|
||||
// Without a link of our own, the share isn't the issue.
|
||||
w = RedditWarnings(RedditCheck{Target: "golang", Info: &reddit.Subreddit{}, History: history, Own: own, Now: now})
|
||||
if len(w) != 0 {
|
||||
t.Errorf("clean post = %q", w)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user