@skilldeck/outreach 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +16 -0
- package/LICENSE +21 -0
- package/README.md +67 -2
- package/bin/outreach.mjs +29 -0
- package/index.mjs +19 -0
- package/package.json +40 -4
- package/skills/reddit-engage/SKILL.md +135 -0
- package/skills/reddit-engage/references/etiquette.md +65 -0
- package/skills/reddit-engage/references/modes.md +46 -0
- package/skills/reddit-engage/scripts/reddit.mjs +872 -0
- package/skills/reddit-setup/SKILL.md +92 -0
- package/skills/reddit-setup/references/oauth-app.md +66 -0
|
@@ -0,0 +1,872 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// outreach / reddit.mjs
|
|
3
|
+
//
|
|
4
|
+
// Careful, capped Reddit engagement from one account. Searches threads, reads
|
|
5
|
+
// subreddit rules, checks drafts (length, links, disclosure, near-duplicates) and
|
|
6
|
+
// posts a reply only when the hard limits in this file allow it:
|
|
7
|
+
//
|
|
8
|
+
// - a daily cap (rolling 24h), a per-subreddit daily cap and a cooldown
|
|
9
|
+
// - never twice in the same thread
|
|
10
|
+
// - review mode: the user's per-draft approval token (--approve <draftId>)
|
|
11
|
+
// - auto mode: a one-time recorded confirmation (config confirm-auto)
|
|
12
|
+
//
|
|
13
|
+
// State lives in ./.outreach/ (config.json, ledger.json, drafts/). Secrets are
|
|
14
|
+
// read from env vars only and never written to disk or printed.
|
|
15
|
+
//
|
|
16
|
+
// node reddit.mjs <command> [args] [--json] [--dir <state dir>]
|
|
17
|
+
//
|
|
18
|
+
// Exit 0 ok, 1 refused or failed, 2 usage or missing environment.
|
|
19
|
+
// Zero dependencies. Node 20+.
|
|
20
|
+
|
|
21
|
+
import fs from 'node:fs'
|
|
22
|
+
import path from 'node:path'
|
|
23
|
+
import crypto from 'node:crypto'
|
|
24
|
+
import { pathToFileURL } from 'node:url'
|
|
25
|
+
|
|
26
|
+
const VERSION = '0.1.0'
|
|
27
|
+
|
|
28
|
+
const HELP = `reddit: capped, approval-gated Reddit engagement
|
|
29
|
+
|
|
30
|
+
node reddit.mjs <command> [args] [--json] [--dir <state dir>]
|
|
31
|
+
|
|
32
|
+
Commands
|
|
33
|
+
doctor check env vars, token, /api/v1/me (read-only fallback if no creds)
|
|
34
|
+
config get [key] show config (or one dotted key)
|
|
35
|
+
config set <key> <value> mode | caps.* | product.* | disclosure | subreddits | keywords
|
|
36
|
+
config confirm-auto record the user's one-time confirmation for auto mode
|
|
37
|
+
search <query> [--sub r] [--limit N] [--time hour|day|week|month|year|all] [--sort new|relevance|top|comments]
|
|
38
|
+
rules <sub> subreddit rules + self-promotion verdict
|
|
39
|
+
thread <id|url> post, state, skip verdict, whether you already replied
|
|
40
|
+
draft-check <file> | --text "..." --thread <id> [--sub r]
|
|
41
|
+
length, links, disclosure, dedupe; prints a draftId when it passes
|
|
42
|
+
post --thread <id> --draft <draftId> [--approve <draftId>] [--dry-run]
|
|
43
|
+
post a checked draft, within caps
|
|
44
|
+
ledger list | today what has been posted
|
|
45
|
+
|
|
46
|
+
Env: REDDIT_CLIENT_ID REDDIT_CLIENT_SECRET REDDIT_USERNAME REDDIT_PASSWORD REDDIT_USER_AGENT
|
|
47
|
+
State: ./.outreach/ (override with --dir or OUTREACH_DIR)
|
|
48
|
+
Exit: 0 ok, 1 refused or failed, 2 usage or environment
|
|
49
|
+
`
|
|
50
|
+
|
|
51
|
+
// ---------------------------------------------------------------------------
|
|
52
|
+
// Defaults and limits
|
|
53
|
+
// ---------------------------------------------------------------------------
|
|
54
|
+
|
|
55
|
+
export const DEFAULT_CONFIG = {
|
|
56
|
+
mode: null, // 'review' | 'auto'
|
|
57
|
+
autoConfirmedAt: null,
|
|
58
|
+
caps: {
|
|
59
|
+
perDay: 5,
|
|
60
|
+
perSubPerDay: 1,
|
|
61
|
+
cooldownMinutes: 30,
|
|
62
|
+
maxThreadAgeDays: 14,
|
|
63
|
+
minChars: 80,
|
|
64
|
+
maxChars: 3000,
|
|
65
|
+
similarity: 0.5,
|
|
66
|
+
},
|
|
67
|
+
product: { name: '', aliases: [], url: '' },
|
|
68
|
+
disclosure: '',
|
|
69
|
+
subreddits: [],
|
|
70
|
+
keywords: [],
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Hard ceilings no config can exceed. Raising volume past these is spam, whatever the config says. */
|
|
74
|
+
export const HARD_LIMITS = {
|
|
75
|
+
perDay: { min: 1, max: 20 },
|
|
76
|
+
perSubPerDay: { min: 1, max: 3 },
|
|
77
|
+
cooldownMinutes: { min: 10, max: 1440 },
|
|
78
|
+
maxThreadAgeDays: { min: 1, max: 180 },
|
|
79
|
+
minChars: { min: 20, max: 2000 },
|
|
80
|
+
maxChars: { min: 200, max: 10000 },
|
|
81
|
+
similarity: { min: 0.2, max: 0.9 },
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const DAY_MS = 24 * 60 * 60 * 1000
|
|
85
|
+
const LIST_KEYS = new Set(['subreddits', 'keywords', 'product.aliases'])
|
|
86
|
+
const STRING_KEYS = new Set(['product.name', 'product.url', 'disclosure'])
|
|
87
|
+
|
|
88
|
+
export class UsageError extends Error {
|
|
89
|
+
constructor(msg) {
|
|
90
|
+
super(msg)
|
|
91
|
+
this.code = 2
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ---------------------------------------------------------------------------
|
|
96
|
+
// State files
|
|
97
|
+
// ---------------------------------------------------------------------------
|
|
98
|
+
|
|
99
|
+
export function stateDir(opts = {}) {
|
|
100
|
+
return path.resolve(opts.dir ?? process.env.OUTREACH_DIR ?? path.join(process.cwd(), '.outreach'))
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function readJson(file, fallback) {
|
|
104
|
+
try {
|
|
105
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
106
|
+
} catch (e) {
|
|
107
|
+
if (e.code === 'ENOENT') return fallback
|
|
108
|
+
throw new Error(`${file}: ${e.message}`)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function writeJson(file, value) {
|
|
113
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
114
|
+
const tmp = `${file}.${process.pid}.tmp`
|
|
115
|
+
fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n')
|
|
116
|
+
fs.renameSync(tmp, file)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function merge(base, over) {
|
|
120
|
+
const out = { ...base }
|
|
121
|
+
for (const [k, v] of Object.entries(over ?? {})) {
|
|
122
|
+
out[k] = v && typeof v === 'object' && !Array.isArray(v) && base[k] && typeof base[k] === 'object' ? merge(base[k], v) : v
|
|
123
|
+
}
|
|
124
|
+
return out
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function loadConfig(dir) {
|
|
128
|
+
return merge(DEFAULT_CONFIG, readJson(path.join(dir, 'config.json'), {}))
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function saveConfig(dir, config) {
|
|
132
|
+
writeJson(path.join(dir, 'config.json'), config)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function loadLedger(dir) {
|
|
136
|
+
const l = readJson(path.join(dir, 'ledger.json'), {})
|
|
137
|
+
return { entries: l.entries ?? [], rateLimitedUntil: l.rateLimitedUntil ?? null }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function saveLedger(dir, ledger) {
|
|
141
|
+
writeJson(path.join(dir, 'ledger.json'), ledger)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function loadDrafts(dir) {
|
|
145
|
+
const d = path.join(dir, 'drafts')
|
|
146
|
+
if (!fs.existsSync(d)) return []
|
|
147
|
+
return fs
|
|
148
|
+
.readdirSync(d)
|
|
149
|
+
.filter((f) => f.endsWith('.json'))
|
|
150
|
+
.map((f) => readJson(path.join(d, f), null))
|
|
151
|
+
.filter(Boolean)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function draftFile(dir, id) {
|
|
155
|
+
if (!/^d_[0-9a-f]{12}$/.test(id ?? '')) throw new UsageError(`not a draft id: ${id}`)
|
|
156
|
+
return path.join(dir, 'drafts', `${id}.json`)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ---------------------------------------------------------------------------
|
|
160
|
+
// Config
|
|
161
|
+
// ---------------------------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
function getPath(obj, key) {
|
|
164
|
+
return key.split('.').reduce((o, k) => (o == null ? undefined : o[k]), obj)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Apply `config set key value` and return the new config. Pure; throws UsageError on bad input. */
|
|
168
|
+
export function setConfigValue(config, key, raw) {
|
|
169
|
+
const next = structuredClone(config)
|
|
170
|
+
if (key === 'autoConfirmedAt') throw new UsageError('autoConfirmedAt is set only by "config confirm-auto", after the user confirms')
|
|
171
|
+
if (key === 'mode') {
|
|
172
|
+
if (raw !== 'review' && raw !== 'auto') throw new UsageError('mode must be "review" or "auto"')
|
|
173
|
+
if (next.mode !== raw) next.autoConfirmedAt = null // switching modes always needs a fresh confirmation
|
|
174
|
+
next.mode = raw
|
|
175
|
+
return next
|
|
176
|
+
}
|
|
177
|
+
if (key.startsWith('caps.')) {
|
|
178
|
+
const name = key.slice(5)
|
|
179
|
+
const lim = HARD_LIMITS[name]
|
|
180
|
+
if (!lim) throw new UsageError(`unknown cap "${name}" (known: ${Object.keys(HARD_LIMITS).join(', ')})`)
|
|
181
|
+
const n = Number(raw)
|
|
182
|
+
if (!Number.isFinite(n)) throw new UsageError(`${key} must be a number`)
|
|
183
|
+
if (n < lim.min || n > lim.max) throw new UsageError(`${key} must be between ${lim.min} and ${lim.max}`)
|
|
184
|
+
next.caps[name] = name === 'similarity' ? n : Math.round(n)
|
|
185
|
+
if (next.mode === 'auto') next.autoConfirmedAt = null // changed limits need re-confirmation
|
|
186
|
+
return next
|
|
187
|
+
}
|
|
188
|
+
if (LIST_KEYS.has(key)) {
|
|
189
|
+
const list = String(raw)
|
|
190
|
+
.split(',')
|
|
191
|
+
.map((s) => s.trim())
|
|
192
|
+
.filter(Boolean)
|
|
193
|
+
.map((s) => (key === 'subreddits' ? s.replace(/^\/?r\//i, '') : s))
|
|
194
|
+
if (key === 'product.aliases') next.product.aliases = list
|
|
195
|
+
else next[key] = list
|
|
196
|
+
return next
|
|
197
|
+
}
|
|
198
|
+
if (STRING_KEYS.has(key)) {
|
|
199
|
+
const [a, b] = key.split('.')
|
|
200
|
+
if (b) next[a][b] = String(raw)
|
|
201
|
+
else next[a] = String(raw)
|
|
202
|
+
return next
|
|
203
|
+
}
|
|
204
|
+
throw new UsageError(`unknown config key "${key}"`)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export function confirmAuto(config, now = Date.now()) {
|
|
208
|
+
if (config.mode !== 'auto') throw new UsageError('set mode to auto first: config set mode auto')
|
|
209
|
+
return { ...config, autoConfirmedAt: new Date(now).toISOString(), autoConfirmedCaps: { ...config.caps } }
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// ---------------------------------------------------------------------------
|
|
213
|
+
// Text checks
|
|
214
|
+
// ---------------------------------------------------------------------------
|
|
215
|
+
|
|
216
|
+
const URL_RE = /\bhttps?:\/\/[^\s)\]>]+|\bwww\.[^\s)\]>]+/gi
|
|
217
|
+
|
|
218
|
+
/** Lowercase, drop URLs and markdown/punctuation, collapse whitespace. */
|
|
219
|
+
export function normalizeText(text) {
|
|
220
|
+
return String(text)
|
|
221
|
+
.toLowerCase()
|
|
222
|
+
.replace(URL_RE, ' ')
|
|
223
|
+
.replace(/[^\p{L}\p{N}\s']/gu, ' ')
|
|
224
|
+
.replace(/'/g, '')
|
|
225
|
+
.replace(/\s+/g, ' ')
|
|
226
|
+
.trim()
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Word n-gram shingles of normalized text. Short texts fall back to single words. */
|
|
230
|
+
export function shingles(text, n = 3) {
|
|
231
|
+
const words = normalizeText(text).split(' ').filter(Boolean)
|
|
232
|
+
const out = new Set()
|
|
233
|
+
if (words.length < n) {
|
|
234
|
+
for (const w of words) out.add(w)
|
|
235
|
+
return out
|
|
236
|
+
}
|
|
237
|
+
for (let i = 0; i + n <= words.length; i++) out.add(words.slice(i, i + n).join(' '))
|
|
238
|
+
return out
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export function jaccard(a, b) {
|
|
242
|
+
if (a.size === 0 && b.size === 0) return 1
|
|
243
|
+
let inter = 0
|
|
244
|
+
for (const x of a) if (b.has(x)) inter++
|
|
245
|
+
return inter / (a.size + b.size - inter)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export function similarity(textA, textB) {
|
|
249
|
+
return jaccard(shingles(textA), shingles(textB))
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function escapeRe(s) {
|
|
253
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function hostOf(url) {
|
|
257
|
+
try {
|
|
258
|
+
return new URL(/^https?:/i.test(url) ? url : `https://${url}`).hostname.replace(/^www\./, '')
|
|
259
|
+
} catch {
|
|
260
|
+
return ''
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Does the text mention the configured product (name, aliases, or its domain)? */
|
|
265
|
+
export function mentionsProduct(text, product = {}) {
|
|
266
|
+
const names = [product.name, ...(product.aliases ?? [])].filter((s) => s && s.trim().length > 1)
|
|
267
|
+
for (const n of names) if (new RegExp(`(^|[^\\p{L}\\p{N}])${escapeRe(n.trim())}($|[^\\p{L}\\p{N}])`, 'iu').test(text)) return true
|
|
268
|
+
const host = product.url ? hostOf(product.url) : ''
|
|
269
|
+
return Boolean(host && text.toLowerCase().includes(host.toLowerCase()))
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const GENERIC_DISCLOSURE =
|
|
273
|
+
/\b(disclosure|full disclosure|disclaimer|i'?m affiliated|i am affiliated|affiliated with|i (work|worked) (on|at|for)|we (built|make|made|run)|i (built|made|created|founded|maintain|run)|i'?m (the|a|one of the) (founder|co-?founder|developer|dev|maker|author|maintainer|creator|team)|(my|our) (company|product|startup|tool|app|project))\b/i
|
|
274
|
+
|
|
275
|
+
/** Disclosure present: the configured disclosure text (normalized), or a plain first-person affiliation statement. */
|
|
276
|
+
export function hasDisclosure(text, disclosure = '') {
|
|
277
|
+
const d = normalizeText(disclosure)
|
|
278
|
+
if (d && normalizeText(text).includes(d)) return true
|
|
279
|
+
return GENERIC_DISCLOSURE.test(text)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export function linkStats(text) {
|
|
283
|
+
const links = String(text).match(URL_RE) ?? []
|
|
284
|
+
const mdLinks = String(text).match(/\[[^\]]*\]\([^)]+\)/g) ?? []
|
|
285
|
+
const words = normalizeText(String(text).replace(/\[([^\]]*)\]\([^)]+\)/g, '$1')).split(' ').filter(Boolean)
|
|
286
|
+
return { links: links.length, mdLinks: mdLinks.length, words: words.length }
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export function hashText(text) {
|
|
290
|
+
return crypto.createHash('sha256').update(String(text)).digest('hex')
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function draftIdFor(thread, text) {
|
|
294
|
+
return 'd_' + hashText(`${thread}\n${text}`).slice(0, 12)
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Check a draft reply. Pure: pass the config, ledger entries and existing drafts.
|
|
299
|
+
* Returns { ok, draftId?, checks: [{name, ok, detail}], similar: [...], mentionsProduct }.
|
|
300
|
+
*/
|
|
301
|
+
export function checkDraft(text, { thread, config = DEFAULT_CONFIG, ledger = { entries: [] }, drafts = [] } = {}) {
|
|
302
|
+
const caps = { ...DEFAULT_CONFIG.caps, ...config.caps }
|
|
303
|
+
const checks = []
|
|
304
|
+
const add = (name, ok, detail) => checks.push({ name, ok, detail })
|
|
305
|
+
const body = String(text ?? '').trim()
|
|
306
|
+
const id = draftIdFor(thread, body)
|
|
307
|
+
|
|
308
|
+
add('length', body.length >= caps.minChars && body.length <= caps.maxChars, `${body.length} chars (allowed ${caps.minChars}-${caps.maxChars})`)
|
|
309
|
+
|
|
310
|
+
const ls = linkStats(body)
|
|
311
|
+
const linkCount = Math.max(ls.links, ls.mdLinks)
|
|
312
|
+
add('not-links-only', ls.words >= 25 || linkCount === 0, `${ls.words} words of text around ${linkCount} link(s); a reply must help on its own`)
|
|
313
|
+
add('link-count', linkCount <= 2, `${linkCount} link(s) (max 2)`)
|
|
314
|
+
|
|
315
|
+
const product = mentionsProduct(body, config.product)
|
|
316
|
+
add(
|
|
317
|
+
'disclosure',
|
|
318
|
+
!product || hasDisclosure(body, config.disclosure),
|
|
319
|
+
product ? 'mentions the product, so it must disclose your affiliation' : 'no product mention',
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
const already = ledger.entries.find((e) => e.thread === thread)
|
|
323
|
+
add('not-already-replied', !already, already ? `already replied in this thread at ${already.postedAt}` : 'no prior reply in ledger')
|
|
324
|
+
|
|
325
|
+
const similar = []
|
|
326
|
+
for (const e of ledger.entries) {
|
|
327
|
+
const s = similarity(body, e.text ?? '')
|
|
328
|
+
if (s >= caps.similarity) similar.push({ source: 'ledger', thread: e.thread, subreddit: e.subreddit, similarity: round(s) })
|
|
329
|
+
}
|
|
330
|
+
for (const d of drafts) {
|
|
331
|
+
if (d.id === id || d.status === 'posted') continue
|
|
332
|
+
const s = similarity(body, d.text ?? '')
|
|
333
|
+
if (s >= caps.similarity) similar.push({ source: 'draft', draftId: d.id, thread: d.thread, similarity: round(s) })
|
|
334
|
+
}
|
|
335
|
+
add('not-duplicate', similar.length === 0, similar.length ? `${similar.length} near-duplicate(s) at >= ${caps.similarity} similarity; write for this thread` : 'unique')
|
|
336
|
+
|
|
337
|
+
const ok = checks.every((c) => c.ok)
|
|
338
|
+
return { ok, draftId: ok ? id : undefined, checks, similar, mentionsProduct: product, chars: body.length }
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const round = (n) => Math.round(n * 100) / 100
|
|
342
|
+
|
|
343
|
+
// ---------------------------------------------------------------------------
|
|
344
|
+
// Rules, threads, caps
|
|
345
|
+
// ---------------------------------------------------------------------------
|
|
346
|
+
|
|
347
|
+
const PROMO_BANNED = [
|
|
348
|
+
/\bno\s+(self[-\s]?promo(tion|ting)?|promo(tion)?|advertis(ing|ements?)|spam(ming)?|marketing|solicitation|commercial|plugs?|shilling)\b/i,
|
|
349
|
+
/\bself[-\s]?promo(tion)?\b[^.]{0,40}\b(not allowed|prohibited|banned|forbidden|will be removed|is not permitted)\b/i,
|
|
350
|
+
/\b(advertising|promotion|promoting)\b[^.]{0,40}\b(not allowed|prohibited|banned|forbidden|will be removed)\b/i,
|
|
351
|
+
/\bdo not (promote|advertise|self[-\s]?promote|plug)\b/i,
|
|
352
|
+
/\bdon'?t (promote|advertise|self[-\s]?promote|plug)\b/i,
|
|
353
|
+
]
|
|
354
|
+
const PROMO_LIMITED = [/\b10\s?%|\b9:1\b|\bratio\b/i, /\bself[-\s]?promo(tion)?\b/i, /\bpromot(e|ion|ing)\b/i, /\badvertis/i, /\baffiliat/i, /\breferral/i]
|
|
355
|
+
|
|
356
|
+
/** Read a subreddit's rules and decide how it treats self-promotion. */
|
|
357
|
+
export function assessRules(rules = []) {
|
|
358
|
+
const matched = { banned: [], limited: [] }
|
|
359
|
+
for (const r of rules) {
|
|
360
|
+
const text = `${r.short_name ?? ''}. ${r.description ?? ''} ${r.violation_reason ?? ''}`
|
|
361
|
+
if (PROMO_BANNED.some((re) => re.test(text))) matched.banned.push(r.short_name ?? text.slice(0, 80))
|
|
362
|
+
else if (PROMO_LIMITED.some((re) => re.test(text))) matched.limited.push(r.short_name ?? text.slice(0, 80))
|
|
363
|
+
}
|
|
364
|
+
const selfPromo = matched.banned.length ? 'banned' : matched.limited.length ? 'limited' : 'unspecified'
|
|
365
|
+
return { selfPromo, matched: matched.banned.length ? matched.banned : matched.limited, ruleCount: rules.length }
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** Accept a bare id, t3_ fullname, or any reddit comments URL. */
|
|
369
|
+
export function parseThreadId(input) {
|
|
370
|
+
const s = String(input ?? '').trim()
|
|
371
|
+
const m = s.match(/\/comments\/([a-z0-9]+)/i) ?? s.match(/^t3_([a-z0-9]+)$/i) ?? s.match(/^([a-z0-9]{4,12})$/i)
|
|
372
|
+
if (!m) throw new UsageError(`not a thread id or URL: ${input}`)
|
|
373
|
+
return m[1].toLowerCase()
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export function normalizeSub(s) {
|
|
377
|
+
const v = String(s ?? '').trim().replace(/^\/?r\//i, '')
|
|
378
|
+
if (!/^[A-Za-z0-9_]{2,21}$/.test(v)) throw new UsageError(`not a subreddit name: ${s}`)
|
|
379
|
+
return v
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function postSummary(d, now = Date.now()) {
|
|
383
|
+
return {
|
|
384
|
+
id: d.id,
|
|
385
|
+
subreddit: d.subreddit,
|
|
386
|
+
title: d.title,
|
|
387
|
+
author: d.author,
|
|
388
|
+
createdUtc: d.created_utc,
|
|
389
|
+
ageHours: d.created_utc ? Math.round((now / 1000 - d.created_utc) / 360) / 10 : null,
|
|
390
|
+
numComments: d.num_comments,
|
|
391
|
+
score: d.score,
|
|
392
|
+
locked: Boolean(d.locked),
|
|
393
|
+
archived: Boolean(d.archived),
|
|
394
|
+
removed: Boolean(d.removed_by_category) || d.selftext === '[removed]',
|
|
395
|
+
over18: Boolean(d.over_18),
|
|
396
|
+
permalink: d.permalink ? `https://www.reddit.com${d.permalink}` : undefined,
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function flattenComments(children = [], out = []) {
|
|
401
|
+
for (const c of children) {
|
|
402
|
+
if (c?.kind !== 't1') continue
|
|
403
|
+
out.push({ id: c.data.id, author: c.data.author, body: c.data.body, createdUtc: c.data.created_utc })
|
|
404
|
+
if (c.data.replies && typeof c.data.replies === 'object') flattenComments(c.data.replies.data?.children, out)
|
|
405
|
+
}
|
|
406
|
+
return out
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Parse the /comments/<id> response into { post, comments }. */
|
|
410
|
+
export function parseThread(json, now = Date.now()) {
|
|
411
|
+
if (!Array.isArray(json) || !json[0]?.data?.children?.[0]) throw new Error('unexpected thread response')
|
|
412
|
+
const post = postSummary(json[0].data.children[0].data, now)
|
|
413
|
+
post.selftext = json[0].data.children[0].data.selftext ?? ''
|
|
414
|
+
const comments = flattenComments(json[1]?.data?.children)
|
|
415
|
+
return { post, comments }
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Should we skip this thread? Pure. */
|
|
419
|
+
export function assessThread({ post, comments = [] }, { username, maxAgeDays = DEFAULT_CONFIG.caps.maxThreadAgeDays, ledger = { entries: [] }, now = Date.now() } = {}) {
|
|
420
|
+
const reasons = []
|
|
421
|
+
if (post.locked) reasons.push('locked')
|
|
422
|
+
if (post.archived) reasons.push('archived')
|
|
423
|
+
if (post.removed) reasons.push('removed')
|
|
424
|
+
if (post.createdUtc && now - post.createdUtc * 1000 > maxAgeDays * DAY_MS) reasons.push(`older than ${maxAgeDays} days`)
|
|
425
|
+
const me = username?.toLowerCase()
|
|
426
|
+
if (me && (post.author?.toLowerCase() === me || comments.some((c) => c.author?.toLowerCase() === me))) reasons.push('you already posted in this thread')
|
|
427
|
+
if (ledger.entries.some((e) => e.thread === post.id)) reasons.push('already in the ledger')
|
|
428
|
+
return { skip: reasons.length > 0, reasons }
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Hard caps. Pure. `subreddit` may be undefined for the pre-network pass.
|
|
433
|
+
* Returns a list of refusal reasons (empty means allowed).
|
|
434
|
+
*/
|
|
435
|
+
export function checkCaps(ledger, { thread, subreddit, now = Date.now(), caps = DEFAULT_CONFIG.caps } = {}) {
|
|
436
|
+
const c = { ...DEFAULT_CONFIG.caps, ...caps }
|
|
437
|
+
const reasons = []
|
|
438
|
+
const entries = ledger.entries ?? []
|
|
439
|
+
if (ledger.rateLimitedUntil && now < Date.parse(ledger.rateLimitedUntil)) reasons.push(`Reddit rate limit in effect until ${ledger.rateLimitedUntil}`)
|
|
440
|
+
if (thread && entries.some((e) => e.thread === thread)) reasons.push('already replied in this thread (never twice in one thread)')
|
|
441
|
+
const recent = entries.filter((e) => now - Date.parse(e.postedAt) < DAY_MS)
|
|
442
|
+
if (recent.length >= c.perDay) reasons.push(`daily cap reached: ${recent.length}/${c.perDay} in the last 24h`)
|
|
443
|
+
if (subreddit) {
|
|
444
|
+
const inSub = recent.filter((e) => e.subreddit?.toLowerCase() === subreddit.toLowerCase())
|
|
445
|
+
if (inSub.length >= c.perSubPerDay) reasons.push(`subreddit cap reached: ${inSub.length}/${c.perSubPerDay} in r/${subreddit} in the last 24h`)
|
|
446
|
+
}
|
|
447
|
+
const last = entries.reduce((m, e) => Math.max(m, Date.parse(e.postedAt) || 0), 0)
|
|
448
|
+
const waitMs = last + c.cooldownMinutes * 60000 - now
|
|
449
|
+
if (last && waitMs > 0) reasons.push(`cooldown: wait ${Math.ceil(waitMs / 60000)} more minute(s) (cooldown ${c.cooldownMinutes}m)`)
|
|
450
|
+
return reasons
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
export function todaySummary(ledger, { now = Date.now(), caps = DEFAULT_CONFIG.caps } = {}) {
|
|
454
|
+
const c = { ...DEFAULT_CONFIG.caps, ...caps }
|
|
455
|
+
const recent = ledger.entries.filter((e) => now - Date.parse(e.postedAt) < DAY_MS)
|
|
456
|
+
const bySub = {}
|
|
457
|
+
for (const e of recent) bySub[e.subreddit] = (bySub[e.subreddit] ?? 0) + 1
|
|
458
|
+
const last = ledger.entries.reduce((m, e) => Math.max(m, Date.parse(e.postedAt) || 0), 0)
|
|
459
|
+
const nextAt = last ? Math.max(now, last + c.cooldownMinutes * 60000) : now
|
|
460
|
+
return { window: 'last 24h', posted: recent.length, cap: c.perDay, remaining: Math.max(0, c.perDay - recent.length), bySubreddit: bySub, perSubCap: c.perSubPerDay, nextAllowedAt: new Date(nextAt).toISOString(), entries: recent }
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// ---------------------------------------------------------------------------
|
|
464
|
+
// Reddit client (fetch injectable)
|
|
465
|
+
// ---------------------------------------------------------------------------
|
|
466
|
+
|
|
467
|
+
export const ENV_KEYS = ['REDDIT_CLIENT_ID', 'REDDIT_CLIENT_SECRET', 'REDDIT_USERNAME', 'REDDIT_PASSWORD', 'REDDIT_USER_AGENT']
|
|
468
|
+
const READONLY_UA = `node:skilldeck-outreach:${VERSION} (read-only)`
|
|
469
|
+
|
|
470
|
+
export function envStatus(env = process.env) {
|
|
471
|
+
const missing = ENV_KEYS.filter((k) => !env[k])
|
|
472
|
+
const ua = env.REDDIT_USER_AGENT ?? ''
|
|
473
|
+
const uaOk = /\S+:\S+:\S+.*\(by \/?u\/[A-Za-z0-9_-]+\)/i.test(ua)
|
|
474
|
+
return { complete: missing.length === 0, missing, userAgentOk: uaOk, readOnly: missing.length > 0 }
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
export class RedditError extends Error {
|
|
478
|
+
constructor(msg, { status, retryAfterSec } = {}) {
|
|
479
|
+
super(msg)
|
|
480
|
+
this.status = status
|
|
481
|
+
this.retryAfterSec = retryAfterSec
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
function rateInfo(res) {
|
|
486
|
+
const h = (k) => res.headers?.get?.(k)
|
|
487
|
+
const num = (v) => (v == null || v === '' ? undefined : Number(v))
|
|
488
|
+
return { remaining: num(h('x-ratelimit-remaining')), used: num(h('x-ratelimit-used')), resetSec: num(h('x-ratelimit-reset')), retryAfterSec: num(h('retry-after')) }
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
export function createClient({ fetch: f = globalThis.fetch, env = process.env } = {}) {
|
|
492
|
+
const st = envStatus(env)
|
|
493
|
+
const ua = env.REDDIT_USER_AGENT || READONLY_UA
|
|
494
|
+
let token = null
|
|
495
|
+
let lastRate = {}
|
|
496
|
+
|
|
497
|
+
async function call(url, init = {}) {
|
|
498
|
+
const res = await f(url, { ...init, headers: { 'User-Agent': ua, ...(init.headers ?? {}) } })
|
|
499
|
+
lastRate = rateInfo(res)
|
|
500
|
+
if (res.status === 429) {
|
|
501
|
+
const wait = lastRate.retryAfterSec ?? lastRate.resetSec ?? 60
|
|
502
|
+
throw new RedditError(`Reddit rate limit (429); retry after ${Math.ceil(wait)}s`, { status: 429, retryAfterSec: wait })
|
|
503
|
+
}
|
|
504
|
+
if (lastRate.remaining !== undefined && lastRate.remaining < 1 && lastRate.resetSec) {
|
|
505
|
+
// Out of budget: say so; the next call would 429.
|
|
506
|
+
lastRate.exhausted = true
|
|
507
|
+
}
|
|
508
|
+
const text = await res.text()
|
|
509
|
+
let json
|
|
510
|
+
try {
|
|
511
|
+
json = text ? JSON.parse(text) : {}
|
|
512
|
+
} catch {
|
|
513
|
+
json = undefined
|
|
514
|
+
}
|
|
515
|
+
if (!res.ok) {
|
|
516
|
+
const msg = json?.message ?? json?.error ?? text.slice(0, 200)
|
|
517
|
+
throw new RedditError(`${init.method ?? 'GET'} ${new URL(url).pathname} -> ${res.status} ${msg}`, { status: res.status })
|
|
518
|
+
}
|
|
519
|
+
if (json === undefined) throw new RedditError(`non-JSON response from ${new URL(url).pathname}`, { status: res.status })
|
|
520
|
+
return json
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
async function auth() {
|
|
524
|
+
if (token) return token
|
|
525
|
+
if (!st.complete) throw new UsageError(`missing env: ${st.missing.join(', ')} (see the reddit-setup skill)`)
|
|
526
|
+
const basic = Buffer.from(`${env.REDDIT_CLIENT_ID}:${env.REDDIT_CLIENT_SECRET}`).toString('base64')
|
|
527
|
+
const body = new URLSearchParams({ grant_type: 'password', username: env.REDDIT_USERNAME, password: env.REDDIT_PASSWORD })
|
|
528
|
+
const json = await call('https://www.reddit.com/api/v1/access_token', {
|
|
529
|
+
method: 'POST',
|
|
530
|
+
headers: { Authorization: `Basic ${basic}`, 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
531
|
+
body: body.toString(),
|
|
532
|
+
})
|
|
533
|
+
if (!json.access_token) throw new RedditError(`token request failed: ${json.error ?? 'no access_token'} (check app type is "script" and the credentials)`, { status: 401 })
|
|
534
|
+
token = { access: json.access_token, scope: json.scope, expiresIn: json.expires_in }
|
|
535
|
+
return token
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/** GET a listing path. Uses OAuth when creds exist, public .json otherwise. */
|
|
539
|
+
async function get(p, params = {}) {
|
|
540
|
+
const qs = new URLSearchParams({ raw_json: '1', ...Object.fromEntries(Object.entries(params).filter(([, v]) => v !== undefined && v !== '')) })
|
|
541
|
+
if (st.complete) {
|
|
542
|
+
const t = await auth()
|
|
543
|
+
return call(`https://oauth.reddit.com${p}?${qs}`, { headers: { Authorization: `bearer ${t.access}` } })
|
|
544
|
+
}
|
|
545
|
+
return call(`https://www.reddit.com${p}.json?${qs}`)
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
async function post(p, form) {
|
|
549
|
+
const t = await auth()
|
|
550
|
+
return call(`https://oauth.reddit.com${p}`, {
|
|
551
|
+
method: 'POST',
|
|
552
|
+
headers: { Authorization: `bearer ${t.access}`, 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
553
|
+
body: new URLSearchParams(form).toString(),
|
|
554
|
+
})
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
return { get, post, auth, env: st, rate: () => lastRate, username: env.REDDIT_USERNAME }
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// ---------------------------------------------------------------------------
|
|
561
|
+
// Commands (each returns { code, data, text })
|
|
562
|
+
// ---------------------------------------------------------------------------
|
|
563
|
+
|
|
564
|
+
export async function doctor(ctx) {
|
|
565
|
+
const st = envStatus(ctx.env)
|
|
566
|
+
const data = { env: { present: ENV_KEYS.filter((k) => !st.missing.includes(k)), missing: st.missing }, userAgentOk: st.userAgentOk }
|
|
567
|
+
if (!st.complete) {
|
|
568
|
+
data.mode = 'read-only'
|
|
569
|
+
data.note = 'Without all five env vars only public .json reads work (search, rules, thread). Posting is disabled.'
|
|
570
|
+
return { code: 2, data, text: `read-only: missing ${st.missing.join(', ')}\n${data.note}` }
|
|
571
|
+
}
|
|
572
|
+
const client = createClient(ctx)
|
|
573
|
+
try {
|
|
574
|
+
const t = await client.auth()
|
|
575
|
+
const me = await client.get('/api/v1/me')
|
|
576
|
+
data.mode = 'authenticated'
|
|
577
|
+
data.scope = t.scope
|
|
578
|
+
data.me = { name: me.name, commentKarma: me.comment_karma, linkKarma: me.link_karma, created: me.created_utc ? new Date(me.created_utc * 1000).toISOString().slice(0, 10) : undefined, verifiedEmail: me.has_verified_email }
|
|
579
|
+
data.rate = client.rate()
|
|
580
|
+
const warn = []
|
|
581
|
+
if (!st.userAgentOk) warn.push('REDDIT_USER_AGENT should look like "<platform>:<app id>:<version> (by /u/<username>)"')
|
|
582
|
+
if (me.name && me.name.toLowerCase() !== ctx.env.REDDIT_USERNAME.toLowerCase()) warn.push('token belongs to a different user than REDDIT_USERNAME')
|
|
583
|
+
data.warnings = warn
|
|
584
|
+
return { code: 0, data, text: [`ok: authenticated as u/${me.name} (scope: ${t.scope ?? '*'})`, `karma: ${me.comment_karma ?? '?'} comment / ${me.link_karma ?? '?'} link`, ...warn.map((w) => `warning: ${w}`)].join('\n') }
|
|
585
|
+
} catch (e) {
|
|
586
|
+
data.mode = 'error'
|
|
587
|
+
data.error = e.message
|
|
588
|
+
return { code: e instanceof UsageError ? 2 : 1, data, text: `failed: ${e.message}` }
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
export async function search(ctx, query, { sub, limit = 25, time = 'week', sort = 'new' } = {}) {
|
|
593
|
+
if (!query) throw new UsageError('search needs a query')
|
|
594
|
+
const client = createClient(ctx)
|
|
595
|
+
const p = sub ? `/r/${normalizeSub(sub)}/search` : '/search'
|
|
596
|
+
const json = await client.get(p, { q: query, restrict_sr: sub ? '1' : undefined, sort, t: time, limit: String(Math.min(100, Number(limit) || 25)), type: 'link' })
|
|
597
|
+
const ledger = loadLedger(ctx.dir)
|
|
598
|
+
const posts = (json?.data?.children ?? []).filter((c) => c.kind === 't3').map((c) => ({ ...postSummary(c.data, ctx.now), inLedger: ledger.entries.some((e) => e.thread === c.data.id) }))
|
|
599
|
+
const lines = posts.map((p) => `${p.id} r/${p.subreddit} ${p.ageHours}h ${p.numComments}c${p.locked ? ' LOCKED' : ''}${p.archived ? ' ARCHIVED' : ''}${p.inLedger ? ' REPLIED' : ''} ${p.title}`)
|
|
600
|
+
return { code: 0, data: { query, sub, posts }, text: lines.join('\n') || 'no results' }
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
export async function rules(ctx, sub) {
|
|
604
|
+
const name = normalizeSub(sub)
|
|
605
|
+
const client = createClient(ctx)
|
|
606
|
+
const json = await client.get(`/r/${name}/about/rules`)
|
|
607
|
+
const list = (json.rules ?? []).map((r) => ({ short_name: r.short_name, description: r.description, kind: r.kind, violation_reason: r.violation_reason }))
|
|
608
|
+
const verdict = assessRules(list)
|
|
609
|
+
const text = [`r/${name}: self-promotion ${verdict.selfPromo}${verdict.matched.length ? ` (${verdict.matched.join('; ')})` : ''}`, ...list.map((r, i) => `${i + 1}. ${r.short_name}`)].join('\n')
|
|
610
|
+
return { code: 0, data: { subreddit: name, rules: list, ...verdict }, text }
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
export async function thread(ctx, input) {
|
|
614
|
+
const id = parseThreadId(input)
|
|
615
|
+
const client = createClient(ctx)
|
|
616
|
+
const json = await client.get(`/comments/${id}`, { limit: '200', depth: '3' })
|
|
617
|
+
const t = parseThread(json, ctx.now)
|
|
618
|
+
const config = loadConfig(ctx.dir)
|
|
619
|
+
const verdict = assessThread(t, { username: ctx.env.REDDIT_USERNAME, maxAgeDays: config.caps.maxThreadAgeDays, ledger: loadLedger(ctx.dir), now: ctx.now })
|
|
620
|
+
const p = t.post
|
|
621
|
+
const text = [
|
|
622
|
+
`${p.id} r/${p.subreddit} ${p.ageHours}h old ${p.numComments} comments`,
|
|
623
|
+
p.title,
|
|
624
|
+
p.permalink,
|
|
625
|
+
verdict.skip ? `SKIP: ${verdict.reasons.join('; ')}` : 'ok to consider',
|
|
626
|
+
'',
|
|
627
|
+
p.selftext.slice(0, 1500),
|
|
628
|
+
'',
|
|
629
|
+
...t.comments.slice(0, 15).map((c) => `- u/${c.author}: ${String(c.body).replace(/\s+/g, ' ').slice(0, 200)}`),
|
|
630
|
+
].join('\n')
|
|
631
|
+
return { code: 0, data: { ...t, ...verdict }, text }
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
export function draftCheck(ctx, text, { thread: threadInput, sub } = {}) {
|
|
635
|
+
if (!threadInput) throw new UsageError('draft-check needs --thread <id>')
|
|
636
|
+
if (!text || !String(text).trim()) throw new UsageError('draft-check needs a file or --text')
|
|
637
|
+
const thread = parseThreadId(threadInput)
|
|
638
|
+
const config = loadConfig(ctx.dir)
|
|
639
|
+
const ledger = loadLedger(ctx.dir)
|
|
640
|
+
const drafts = loadDrafts(ctx.dir)
|
|
641
|
+
const body = String(text).trim()
|
|
642
|
+
const r = checkDraft(body, { thread, config, ledger, drafts })
|
|
643
|
+
if (r.ok) {
|
|
644
|
+
writeJson(draftFile(ctx.dir, r.draftId), {
|
|
645
|
+
id: r.draftId,
|
|
646
|
+
thread,
|
|
647
|
+
subreddit: sub ? normalizeSub(sub) : undefined,
|
|
648
|
+
text: body,
|
|
649
|
+
hash: hashText(body),
|
|
650
|
+
mentionsProduct: r.mentionsProduct,
|
|
651
|
+
status: 'ready',
|
|
652
|
+
checkedAt: new Date(ctx.now).toISOString(),
|
|
653
|
+
})
|
|
654
|
+
}
|
|
655
|
+
const lines = r.checks.map((c) => `${c.ok ? 'pass' : 'FAIL'} ${c.name.padEnd(20)} ${c.detail}`)
|
|
656
|
+
lines.push(r.ok ? `draftId: ${r.draftId}` : 'not saved: fix the failures and re-run')
|
|
657
|
+
return { code: r.ok ? 0 : 1, data: { thread, ...r }, text: lines.join('\n') }
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/** Post a checked draft. Every gate here is enforced in code, regardless of what the agent was told. */
|
|
661
|
+
export async function postDraft(ctx, { thread: threadInput, draft: draftId, approve, dryRun = false } = {}) {
|
|
662
|
+
if (!threadInput || !draftId) throw new UsageError('post needs --thread <id> --draft <draftId>')
|
|
663
|
+
const thread = parseThreadId(threadInput)
|
|
664
|
+
const config = loadConfig(ctx.dir)
|
|
665
|
+
const refuse = (reasons, extra = {}) => ({ code: 1, data: { posted: false, refused: true, reasons, ...extra }, text: `refused:\n${reasons.map((r) => ` - ${r}`).join('\n')}` })
|
|
666
|
+
|
|
667
|
+
// 1. Mode gate
|
|
668
|
+
if (config.mode !== 'review' && config.mode !== 'auto') return refuse(['no mode chosen: ask the user, then "config set mode review|auto"'])
|
|
669
|
+
if (config.mode === 'review' && approve !== draftId) return refuse([`review mode: needs the user's explicit approval of this exact draft (--approve ${draftId})`])
|
|
670
|
+
if (config.mode === 'auto' && !config.autoConfirmedAt) return refuse(['auto mode is not confirmed: show the user the caps and run "config confirm-auto" only after they agree'])
|
|
671
|
+
|
|
672
|
+
// 2. Draft integrity
|
|
673
|
+
const file = draftFile(ctx.dir, draftId)
|
|
674
|
+
const d = readJson(file, null)
|
|
675
|
+
if (!d) return refuse([`no checked draft ${draftId}: run draft-check first`])
|
|
676
|
+
if (d.thread !== thread) return refuse([`draft ${draftId} was checked for thread ${d.thread}, not ${thread}`])
|
|
677
|
+
if (d.status === 'posted') return refuse([`draft ${draftId} was already posted`])
|
|
678
|
+
if (hashText(d.text) !== d.hash) return refuse([`draft ${draftId} changed after it was checked: re-run draft-check`])
|
|
679
|
+
|
|
680
|
+
// 3. Caps before any network
|
|
681
|
+
const ledger = loadLedger(ctx.dir)
|
|
682
|
+
const pre = checkCaps(ledger, { thread, now: ctx.now, caps: config.caps })
|
|
683
|
+
if (pre.length) return refuse(pre)
|
|
684
|
+
|
|
685
|
+
// 4. Thread state, per-subreddit cap and rules (network, read-only)
|
|
686
|
+
const st = envStatus(ctx.env)
|
|
687
|
+
if (!st.complete) return { code: 2, data: { posted: false, missing: st.missing }, text: `cannot post: missing env ${st.missing.join(', ')}` }
|
|
688
|
+
const client = createClient(ctx)
|
|
689
|
+
let t
|
|
690
|
+
let verdict
|
|
691
|
+
try {
|
|
692
|
+
t = parseThread(await client.get(`/comments/${thread}`, { limit: '200', depth: '3' }), ctx.now)
|
|
693
|
+
const r = await client.get(`/r/${t.post.subreddit}/about/rules`)
|
|
694
|
+
verdict = assessRules(r.rules ?? [])
|
|
695
|
+
} catch (e) {
|
|
696
|
+
return handleNetError(ctx, e)
|
|
697
|
+
}
|
|
698
|
+
const reasons = [
|
|
699
|
+
...assessThread(t, { username: ctx.env.REDDIT_USERNAME, maxAgeDays: config.caps.maxThreadAgeDays, ledger, now: ctx.now }).reasons,
|
|
700
|
+
...checkCaps(ledger, { thread, subreddit: t.post.subreddit, now: ctx.now, caps: config.caps }),
|
|
701
|
+
]
|
|
702
|
+
if (d.mentionsProduct && verdict.selfPromo === 'banned') reasons.push(`r/${t.post.subreddit} bans self-promotion (${verdict.matched.join('; ')}) and this draft mentions the product`)
|
|
703
|
+
const unique = [...new Set(reasons)]
|
|
704
|
+
if (unique.length) return refuse(unique, { subreddit: t.post.subreddit })
|
|
705
|
+
|
|
706
|
+
if (dryRun) return { code: 0, data: { posted: false, dryRun: true, thread, subreddit: t.post.subreddit, draftId, mode: config.mode }, text: `dry run: would post ${draftId} to r/${t.post.subreddit} thread ${thread}` }
|
|
707
|
+
|
|
708
|
+
// 5. Post
|
|
709
|
+
let res
|
|
710
|
+
try {
|
|
711
|
+
res = await client.post('/api/comment', { api_type: 'json', thing_id: `t3_${thread}`, text: d.text })
|
|
712
|
+
} catch (e) {
|
|
713
|
+
return handleNetError(ctx, e)
|
|
714
|
+
}
|
|
715
|
+
const errors = res?.json?.errors ?? []
|
|
716
|
+
if (errors.length) {
|
|
717
|
+
const rl = errors.find((x) => x[0] === 'RATELIMIT')
|
|
718
|
+
if (rl) recordRateLimit(ctx, parseRateLimitMessage(rl[1]))
|
|
719
|
+
return refuse(errors.map((x) => `reddit: ${x[0]} ${x[1] ?? ''}`.trim()))
|
|
720
|
+
}
|
|
721
|
+
const thing = res?.json?.data?.things?.[0]?.data ?? {}
|
|
722
|
+
const entry = {
|
|
723
|
+
thread,
|
|
724
|
+
subreddit: t.post.subreddit,
|
|
725
|
+
draftId,
|
|
726
|
+
commentId: thing.id ?? thing.name,
|
|
727
|
+
permalink: thing.permalink ? `https://www.reddit.com${thing.permalink}` : undefined,
|
|
728
|
+
text: d.text,
|
|
729
|
+
mode: config.mode,
|
|
730
|
+
approvedBy: config.mode === 'review' ? 'user' : 'auto-confirmed',
|
|
731
|
+
postedAt: new Date(ctx.now).toISOString(),
|
|
732
|
+
}
|
|
733
|
+
const fresh = loadLedger(ctx.dir)
|
|
734
|
+
fresh.entries.push(entry)
|
|
735
|
+
saveLedger(ctx.dir, fresh)
|
|
736
|
+
writeJson(file, { ...d, status: 'posted', postedAt: entry.postedAt, commentId: entry.commentId })
|
|
737
|
+
return { code: 0, data: { posted: true, ...entry }, text: `posted ${draftId} to r/${entry.subreddit}: ${entry.permalink ?? entry.commentId}` }
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
export function parseRateLimitMessage(msg = '') {
|
|
741
|
+
const m = String(msg).match(/(\d+)\s*(second|minute|hour)/i)
|
|
742
|
+
if (!m) return 600
|
|
743
|
+
const n = Number(m[1])
|
|
744
|
+
return /hour/i.test(m[2]) ? n * 3600 : /minute/i.test(m[2]) ? n * 60 : n
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
function recordRateLimit(ctx, seconds) {
|
|
748
|
+
const l = loadLedger(ctx.dir)
|
|
749
|
+
l.rateLimitedUntil = new Date(ctx.now + seconds * 1000).toISOString()
|
|
750
|
+
saveLedger(ctx.dir, l)
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
function handleNetError(ctx, e) {
|
|
754
|
+
if (e instanceof UsageError) return { code: 2, data: { posted: false, error: e.message }, text: e.message }
|
|
755
|
+
if (e.status === 429) recordRateLimit(ctx, e.retryAfterSec ?? 60)
|
|
756
|
+
return { code: 1, data: { posted: false, error: e.message, status: e.status }, text: `failed: ${e.message}` }
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
export function ledgerCmd(ctx, sub = 'list') {
|
|
760
|
+
const ledger = loadLedger(ctx.dir)
|
|
761
|
+
const config = loadConfig(ctx.dir)
|
|
762
|
+
if (sub === 'today') {
|
|
763
|
+
const s = todaySummary(ledger, { now: ctx.now, caps: config.caps })
|
|
764
|
+
const text = [`${s.posted}/${s.cap} in the last 24h, ${s.remaining} left; next allowed ${s.nextAllowedAt}`, ...Object.entries(s.bySubreddit).map(([k, v]) => ` r/${k}: ${v}/${s.perSubCap}`)].join('\n')
|
|
765
|
+
return { code: 0, data: s, text }
|
|
766
|
+
}
|
|
767
|
+
if (sub !== 'list') throw new UsageError('ledger list | today')
|
|
768
|
+
const text = ledger.entries.map((e) => `${e.postedAt} r/${e.subreddit} ${e.thread} ${e.mode} ${e.permalink ?? e.commentId ?? ''}`).join('\n') || 'ledger is empty'
|
|
769
|
+
return { code: 0, data: ledger, text }
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
export function configCmd(ctx, [action = 'get', key, ...rest]) {
|
|
773
|
+
const config = loadConfig(ctx.dir)
|
|
774
|
+
if (action === 'get') {
|
|
775
|
+
const v = key ? getPath(config, key) : config
|
|
776
|
+
return { code: 0, data: v ?? null, text: typeof v === 'object' ? JSON.stringify(v, null, 2) : String(v ?? '') }
|
|
777
|
+
}
|
|
778
|
+
if (action === 'set') {
|
|
779
|
+
if (!key || rest.length === 0) throw new UsageError('config set <key> <value>')
|
|
780
|
+
const next = setConfigValue(config, key, rest.join(' '))
|
|
781
|
+
saveConfig(ctx.dir, next)
|
|
782
|
+
const note = config.autoConfirmedAt && !next.autoConfirmedAt ? ' (auto confirmation cleared: confirm again with the user)' : ''
|
|
783
|
+
return { code: 0, data: next, text: `${key} = ${JSON.stringify(getPath(next, key))}${note}` }
|
|
784
|
+
}
|
|
785
|
+
if (action === 'confirm-auto') {
|
|
786
|
+
const next = confirmAuto(config, ctx.now)
|
|
787
|
+
saveConfig(ctx.dir, next)
|
|
788
|
+
const c = next.caps
|
|
789
|
+
return { code: 0, data: next, text: `auto mode confirmed at ${next.autoConfirmedAt}: max ${c.perDay}/24h, ${c.perSubPerDay}/subreddit/24h, ${c.cooldownMinutes}m cooldown` }
|
|
790
|
+
}
|
|
791
|
+
throw new UsageError('config get [key] | set <key> <value> | confirm-auto')
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
// ---------------------------------------------------------------------------
|
|
795
|
+
// CLI
|
|
796
|
+
// ---------------------------------------------------------------------------
|
|
797
|
+
|
|
798
|
+
const VALUED = new Set(['--sub', '--limit', '--time', '--sort', '--thread', '--draft', '--approve', '--text', '--dir'])
|
|
799
|
+
|
|
800
|
+
export function parseCli(argv) {
|
|
801
|
+
const flags = {}
|
|
802
|
+
const pos = []
|
|
803
|
+
for (let i = 0; i < argv.length; i++) {
|
|
804
|
+
const a = argv[i]
|
|
805
|
+
if (VALUED.has(a)) {
|
|
806
|
+
if (i + 1 >= argv.length) throw new UsageError(`${a} needs a value`)
|
|
807
|
+
flags[a.slice(2)] = argv[++i]
|
|
808
|
+
} else if (a.startsWith('--')) flags[a.slice(2)] = true
|
|
809
|
+
else pos.push(a)
|
|
810
|
+
}
|
|
811
|
+
return { flags, pos }
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
export async function run(argv, { fetch: f = globalThis.fetch, env = process.env, now = Date.now(), out = process.stdout, err = process.stderr } = {}) {
|
|
815
|
+
let json = argv.includes('--json')
|
|
816
|
+
try {
|
|
817
|
+
if (!argv.length || argv[0] === '--help' || argv[0] === '-h' || argv[0] === 'help') {
|
|
818
|
+
out.write(HELP)
|
|
819
|
+
return argv.length ? 0 : 2
|
|
820
|
+
}
|
|
821
|
+
if (argv[0] === '--version') {
|
|
822
|
+
out.write(VERSION + '\n')
|
|
823
|
+
return 0
|
|
824
|
+
}
|
|
825
|
+
const { flags, pos } = parseCli(argv)
|
|
826
|
+
json = Boolean(flags.json)
|
|
827
|
+
const [cmd, ...args] = pos
|
|
828
|
+
const ctx = { fetch: f, env, now, dir: stateDir({ dir: flags.dir }) }
|
|
829
|
+
let r
|
|
830
|
+
switch (cmd) {
|
|
831
|
+
case 'doctor':
|
|
832
|
+
r = await doctor(ctx)
|
|
833
|
+
break
|
|
834
|
+
case 'config':
|
|
835
|
+
r = configCmd(ctx, args)
|
|
836
|
+
break
|
|
837
|
+
case 'search':
|
|
838
|
+
r = await search(ctx, args.join(' '), { sub: flags.sub, limit: flags.limit, time: flags.time, sort: flags.sort })
|
|
839
|
+
break
|
|
840
|
+
case 'rules':
|
|
841
|
+
if (!args[0]) throw new UsageError('rules <subreddit>')
|
|
842
|
+
r = await rules(ctx, args[0])
|
|
843
|
+
break
|
|
844
|
+
case 'thread':
|
|
845
|
+
if (!args[0]) throw new UsageError('thread <id|url>')
|
|
846
|
+
r = await thread(ctx, args[0])
|
|
847
|
+
break
|
|
848
|
+
case 'draft-check': {
|
|
849
|
+
const text = flags.text ?? (args[0] ? fs.readFileSync(args[0], 'utf8') : undefined)
|
|
850
|
+
r = draftCheck(ctx, text, { thread: flags.thread, sub: flags.sub })
|
|
851
|
+
break
|
|
852
|
+
}
|
|
853
|
+
case 'post':
|
|
854
|
+
r = await postDraft(ctx, { thread: flags.thread, draft: flags.draft, approve: flags.approve, dryRun: Boolean(flags['dry-run']) })
|
|
855
|
+
break
|
|
856
|
+
case 'ledger':
|
|
857
|
+
r = ledgerCmd(ctx, args[0])
|
|
858
|
+
break
|
|
859
|
+
default:
|
|
860
|
+
throw new UsageError(`unknown command "${cmd}" (try --help)`)
|
|
861
|
+
}
|
|
862
|
+
out.write(json ? JSON.stringify({ ok: r.code === 0, ...(r.data && typeof r.data === 'object' && !Array.isArray(r.data) ? r.data : { value: r.data }) }, null, 2) + '\n' : r.text + '\n')
|
|
863
|
+
return r.code
|
|
864
|
+
} catch (e) {
|
|
865
|
+
const code = e instanceof UsageError || e.code === 2 ? 2 : 1
|
|
866
|
+
if (json) out.write(JSON.stringify({ ok: false, error: e.message }) + '\n')
|
|
867
|
+
else err.write(`reddit: ${e.message}\n`)
|
|
868
|
+
return code
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) process.exitCode = await run(process.argv.slice(2))
|