agents-framework 0.3.0__py3-none-any.whl
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.
- agents_framework-0.3.0.dist-info/METADATA +1364 -0
- agents_framework-0.3.0.dist-info/RECORD +50 -0
- agents_framework-0.3.0.dist-info/WHEEL +5 -0
- agents_framework-0.3.0.dist-info/entry_points.txt +2 -0
- agents_framework-0.3.0.dist-info/licenses/LICENSE +661 -0
- agents_framework-0.3.0.dist-info/top_level.txt +1 -0
- framework/__init__.py +0 -0
- framework/__main__.py +9 -0
- framework/action_page.py +1102 -0
- framework/approval_buttons.py +775 -0
- framework/approvals.py +678 -0
- framework/calendar_card.py +276 -0
- framework/cli.py +273 -0
- framework/codex_llm.py +401 -0
- framework/config.py +126 -0
- framework/drafter.py +263 -0
- framework/interfaces.py +96 -0
- framework/llm.py +744 -0
- framework/plugins/__init__.py +147 -0
- framework/plugins/agentmail_source.py +355 -0
- framework/plugins/approval_destination.py +478 -0
- framework/plugins/command_action.py +248 -0
- framework/plugins/digest_destination.py +546 -0
- framework/plugins/email_destination.py +248 -0
- framework/plugins/fanout_destination.py +160 -0
- framework/plugins/github_org_source.py +226 -0
- framework/plugins/github_releases_source.py +420 -0
- framework/plugins/ics_source.py +594 -0
- framework/plugins/llm_scorer.py +411 -0
- framework/plugins/multi_source.py +241 -0
- framework/plugins/reddit_source.py +625 -0
- framework/plugins/regex_scorer.py +93 -0
- framework/plugins/rss_source.py +346 -0
- framework/plugins/signal_destination.py +133 -0
- framework/plugins/slack_destination.py +461 -0
- framework/plugins/slack_draft_action.py +137 -0
- framework/plugins/slack_post_action.py +65 -0
- framework/plugins/slack_workspace_source.py +992 -0
- framework/plugins/twitter_action.py +210 -0
- framework/plugins/websearch_source.py +761 -0
- framework/plugins/wordpress_action.py +413 -0
- framework/proposals.py +246 -0
- framework/registry.py +166 -0
- framework/runlog.py +125 -0
- framework/runner.py +243 -0
- framework/schedule.py +571 -0
- framework/signal_messenger.py +1418 -0
- framework/slack.py +801 -0
- framework/state.py +39 -0
- framework/templating.py +76 -0
|
@@ -0,0 +1,625 @@
|
|
|
1
|
+
"""Reddit source — the v1 reference Source implementation (issue #2).
|
|
2
|
+
|
|
3
|
+
Ported from hq/leads/signals/reddit_monitor.py. Two transports, chosen by
|
|
4
|
+
`auth`:
|
|
5
|
+
|
|
6
|
+
- `auth` absent or `"none"` — the public RSS feeds, no credential. Each
|
|
7
|
+
configured subreddit contributes its newest posts, optionally narrowed by
|
|
8
|
+
per-subreddit search terms. This was the whole of v1.
|
|
9
|
+
- `auth: "oauth"` — the authenticated JSON API, app-only. Needs a Reddit app's
|
|
10
|
+
client id and secret, named by `client_id_env` / `client_secret_env` and
|
|
11
|
+
read from the environment. No password, no user context, no PRAW.
|
|
12
|
+
|
|
13
|
+
Two things carried over from the reference because both were learned the hard
|
|
14
|
+
way:
|
|
15
|
+
|
|
16
|
+
- **Reddit 403s browser-spoofing User-Agents.** Their API policy wants a
|
|
17
|
+
descriptive bot UA, so send one. A Chrome-lookalike UA gets blocked.
|
|
18
|
+
- **Search RSS feeds have been 403ing since roughly March 2026.** A subreddit
|
|
19
|
+
with no `searches` (plain `/new.rss`) is the reliable configuration.
|
|
20
|
+
|
|
21
|
+
Measured while porting, and worse than the reference implies: **`/new.rss`
|
|
22
|
+
itself now rate-limits hard**, returning 429 after only a couple of requests
|
|
23
|
+
from one IP. Two consequences shape this implementation:
|
|
24
|
+
|
|
25
|
+
- Retry with backoff, honouring `Retry-After` when Reddit sends it.
|
|
26
|
+
- A feed that still fails is recorded in `feed_errors` and the run continues,
|
|
27
|
+
but the failure is *not* swallowed. The reference wrapped everything in
|
|
28
|
+
`except Exception: return []`, so a fully rate-limited run looked exactly
|
|
29
|
+
like a quiet day on Reddit. If every feed fails, `fetch()` raises rather
|
|
30
|
+
than reporting a cheerful zero.
|
|
31
|
+
|
|
32
|
+
The rate limiting did prove permanent. From 2026-11-17 every `/new.rss` request
|
|
33
|
+
from one particular address returned 404 or 429, the two codes shuffling across
|
|
34
|
+
subreddits that were demonstrably live — so the status code described the
|
|
35
|
+
caller, not the subreddit — and the leads agent failed 77 consecutive runs
|
|
36
|
+
without fetching anything. That is what `auth: "oauth"` is for.
|
|
37
|
+
|
|
38
|
+
It also fixes the rules fetch. `about/rules.json` has 403ed unauthenticated
|
|
39
|
+
since about 2026-10 (issue #105), which made every draft treat self-promotion as
|
|
40
|
+
forbidden; `oauth.reddit.com/r/<sub>/about/rules` serves the same payload to a
|
|
41
|
+
credentialed caller.
|
|
42
|
+
|
|
43
|
+
Missing credentials under `auth: "oauth"` raise at build time rather than
|
|
44
|
+
falling back to RSS. A silent fallback would turn a credential problem into
|
|
45
|
+
exactly the 404/429 run this transport exists to escape.
|
|
46
|
+
|
|
47
|
+
Scoring deliberately does **not** live here, unlike the reference script, which
|
|
48
|
+
scored inline. Under the plugin contract a Source only produces Signals; the
|
|
49
|
+
Scorer decides what they are worth.
|
|
50
|
+
|
|
51
|
+
Contract: see docs/PLUGIN-CONTRACT.md.
|
|
52
|
+
"""
|
|
53
|
+
from __future__ import annotations
|
|
54
|
+
|
|
55
|
+
import html
|
|
56
|
+
import os
|
|
57
|
+
import re
|
|
58
|
+
import sys
|
|
59
|
+
import time
|
|
60
|
+
from datetime import datetime, timezone
|
|
61
|
+
from urllib.parse import quote
|
|
62
|
+
|
|
63
|
+
import feedparser
|
|
64
|
+
import requests
|
|
65
|
+
|
|
66
|
+
from framework.interfaces import Signal, Source
|
|
67
|
+
from framework.registry import register_source
|
|
68
|
+
|
|
69
|
+
_DEFAULT_USER_AGENT = "voitta-agents:reddit-source/1.0 (+https://github.com/voitta-ai/agents)"
|
|
70
|
+
_SUBREDDIT_RE = re.compile(r"/r/(\w+)/")
|
|
71
|
+
|
|
72
|
+
# Reddit wraps post bodies in its own markers and appends a fixed footer that
|
|
73
|
+
# carries no signal: "submitted by /u/x [link] [comments]".
|
|
74
|
+
_SC_MARKERS = re.compile(r"<!--\s*SC_O(FF|N)\s*-->")
|
|
75
|
+
_RSS_FOOTER = re.compile(
|
|
76
|
+
r"\s*submitted by\s*/?u?/?\S*\s*(\[link\])?\s*(\[comments\])?\s*$",
|
|
77
|
+
re.IGNORECASE | re.DOTALL,
|
|
78
|
+
)
|
|
79
|
+
_BLOCK_END = re.compile(r"</(p|div|li|h[1-6]|blockquote)>|<br\s*/?>", re.IGNORECASE)
|
|
80
|
+
_TAG = re.compile(r"<[^>]+>")
|
|
81
|
+
_WS = re.compile(r"[ \t]+")
|
|
82
|
+
_BLANKS = re.compile(r"\n{3,}")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _clean_html(raw: str) -> str:
|
|
86
|
+
"""Reddit's RSS `summary` is HTML, not text.
|
|
87
|
+
|
|
88
|
+
Left alone it reaches Slack as literal `<div class="md">`, `<br />` and
|
|
89
|
+
` `, and the scorer matches against markup instead of prose. Both are
|
|
90
|
+
fixed here rather than at the destination: markup is an artefact of this
|
|
91
|
+
source's transport, and every consumer downstream wants it gone.
|
|
92
|
+
|
|
93
|
+
Deliberately not a Markdown converter — the text is scored, and bold markers
|
|
94
|
+
would just be more noise to match against. Block-level tags become newlines
|
|
95
|
+
so paragraphs survive; everything else is dropped.
|
|
96
|
+
"""
|
|
97
|
+
if not raw:
|
|
98
|
+
return ""
|
|
99
|
+
text = _SC_MARKERS.sub("", raw)
|
|
100
|
+
text = _BLOCK_END.sub("\n", text)
|
|
101
|
+
text = _TAG.sub("", text)
|
|
102
|
+
text = html.unescape(text)
|
|
103
|
+
#   unescapes to a space, so collapse only after unescaping.
|
|
104
|
+
text = _WS.sub(" ", text)
|
|
105
|
+
text = "\n".join(line.strip() for line in text.splitlines())
|
|
106
|
+
text = _RSS_FOOTER.sub("", text)
|
|
107
|
+
retval = _BLANKS.sub("\n\n", text).strip()
|
|
108
|
+
return retval
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _new_url(subreddit: str) -> str:
|
|
112
|
+
retval = f"https://www.reddit.com/r/{subreddit}/new.rss"
|
|
113
|
+
return retval
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _iso(created_utc: object) -> str:
|
|
117
|
+
"""Reddit's epoch `created_utc` as the ISO string the RSS path already yields.
|
|
118
|
+
|
|
119
|
+
The two transports feed the same Signal, so a consumer must not be able to
|
|
120
|
+
tell which one produced it.
|
|
121
|
+
"""
|
|
122
|
+
try:
|
|
123
|
+
stamp = float(created_utc) # type: ignore[arg-type]
|
|
124
|
+
except (TypeError, ValueError):
|
|
125
|
+
return ""
|
|
126
|
+
retval = datetime.fromtimestamp(stamp, tz=timezone.utc).isoformat()
|
|
127
|
+
return retval
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _search_url(subreddit: str, search: str) -> str:
|
|
131
|
+
retval = (
|
|
132
|
+
f"https://old.reddit.com/r/{subreddit}/search.rss"
|
|
133
|
+
f"?q={quote(search)}&restrict_sr=1&sort=new"
|
|
134
|
+
)
|
|
135
|
+
return retval
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _extract_subreddit(url: str) -> str:
|
|
139
|
+
match = _SUBREDDIT_RE.search(url or "")
|
|
140
|
+
retval = match.group(1) if match else ""
|
|
141
|
+
return retval
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class RedditSource:
|
|
145
|
+
def __init__(
|
|
146
|
+
self,
|
|
147
|
+
subreddits: dict[str, dict],
|
|
148
|
+
user_agent: str = _DEFAULT_USER_AGENT,
|
|
149
|
+
delay_seconds: float = 2.0,
|
|
150
|
+
timeout: int = 15,
|
|
151
|
+
limit_per_feed: int = 25,
|
|
152
|
+
max_retries: int = 2,
|
|
153
|
+
include_rules: bool = False,
|
|
154
|
+
auth: str = "none",
|
|
155
|
+
client_id: str = "",
|
|
156
|
+
client_secret: str = "",
|
|
157
|
+
):
|
|
158
|
+
self.subreddits = subreddits
|
|
159
|
+
self.user_agent = user_agent
|
|
160
|
+
self.delay_seconds = delay_seconds
|
|
161
|
+
self.timeout = timeout
|
|
162
|
+
self.limit_per_feed = limit_per_feed
|
|
163
|
+
self.max_retries = max_retries
|
|
164
|
+
self.include_rules = include_rules
|
|
165
|
+
self.auth = auth
|
|
166
|
+
self.client_id = client_id
|
|
167
|
+
self.client_secret = client_secret
|
|
168
|
+
# Fetched on first use and reused for the rest of the run. Reddit's
|
|
169
|
+
# app-only tokens last about a day; a run lasts seconds.
|
|
170
|
+
self._token = ""
|
|
171
|
+
self.feed_errors: list[tuple[str, str]] = []
|
|
172
|
+
# One (subreddit, url, posts) row per feed that answered, so a run can
|
|
173
|
+
# say how much of its configured supply it actually got.
|
|
174
|
+
self.feed_counts: list[tuple[str, str, int]] = []
|
|
175
|
+
# Rules that could not be read. Separate from feed_errors because they
|
|
176
|
+
# degrade a lead rather than losing one, and must not count toward the
|
|
177
|
+
# all-feeds-failed check that turns a dead run into a raise.
|
|
178
|
+
self.rule_errors: list[tuple[str, str]] = []
|
|
179
|
+
|
|
180
|
+
def _access_token(self) -> str:
|
|
181
|
+
"""An app-only bearer token, fetched once per run and cached.
|
|
182
|
+
|
|
183
|
+
`client_credentials` is the grant for a confidential client, which is
|
|
184
|
+
what Reddit calls a "script" app, and it yields app-only access with no
|
|
185
|
+
user context — all a public listing needs. Deliberately not the
|
|
186
|
+
`password` grant: that would put an account password in the agent's
|
|
187
|
+
environment to read posts that need no account at all.
|
|
188
|
+
"""
|
|
189
|
+
if self._token:
|
|
190
|
+
return self._token
|
|
191
|
+
resp = requests.post(
|
|
192
|
+
_OAUTH_TOKEN_URL,
|
|
193
|
+
auth=(self.client_id, self.client_secret),
|
|
194
|
+
data={"grant_type": "client_credentials"},
|
|
195
|
+
headers={"User-Agent": self.user_agent},
|
|
196
|
+
timeout=self.timeout,
|
|
197
|
+
)
|
|
198
|
+
if not resp.ok:
|
|
199
|
+
raise RuntimeError(
|
|
200
|
+
f"reddit source: token request returned {resp.status_code} {resp.reason}. "
|
|
201
|
+
"Check the client id and secret, and that the app's type is 'script'."
|
|
202
|
+
)
|
|
203
|
+
try:
|
|
204
|
+
payload = resp.json()
|
|
205
|
+
except ValueError as exc:
|
|
206
|
+
raise RuntimeError(f"reddit source: token reply was not JSON: {exc}") from exc
|
|
207
|
+
token = str((payload or {}).get("access_token") or "")
|
|
208
|
+
if not token:
|
|
209
|
+
raise RuntimeError("reddit source: token reply carried no access_token")
|
|
210
|
+
self._token = token
|
|
211
|
+
return token
|
|
212
|
+
|
|
213
|
+
def _headers(self) -> dict[str, str]:
|
|
214
|
+
"""Request headers for whichever transport is configured.
|
|
215
|
+
|
|
216
|
+
Reddit 403s browser-spoofing User-Agents on both transports, so the
|
|
217
|
+
descriptive UA is not optional on either.
|
|
218
|
+
"""
|
|
219
|
+
headers = {"User-Agent": self.user_agent}
|
|
220
|
+
if self.auth == "oauth":
|
|
221
|
+
headers["Authorization"] = f"bearer {self._access_token()}"
|
|
222
|
+
retval = headers
|
|
223
|
+
return retval
|
|
224
|
+
|
|
225
|
+
def _get(self, url: str, params: dict | None = None) -> requests.Response | None:
|
|
226
|
+
"""GET with backoff on 429. Returns None if the feed stays unavailable.
|
|
227
|
+
|
|
228
|
+
Shared by both transports so that the retry policy, the error recording
|
|
229
|
+
and the all-failed accounting cannot drift apart between them.
|
|
230
|
+
"""
|
|
231
|
+
delay = self.delay_seconds
|
|
232
|
+
for attempt in range(self.max_retries + 1):
|
|
233
|
+
time.sleep(delay)
|
|
234
|
+
resp = requests.get(
|
|
235
|
+
url, headers=self._headers(), params=params, timeout=self.timeout
|
|
236
|
+
)
|
|
237
|
+
if resp.status_code == 429:
|
|
238
|
+
if attempt == self.max_retries:
|
|
239
|
+
self.feed_errors.append((url, "429 rate limited"))
|
|
240
|
+
return None
|
|
241
|
+
retry_after = resp.headers.get("Retry-After")
|
|
242
|
+
delay = float(retry_after) if retry_after and retry_after.isdigit() else delay * 4
|
|
243
|
+
continue
|
|
244
|
+
if resp.status_code == 403:
|
|
245
|
+
why = (
|
|
246
|
+
"403 forbidden (token lacks access, or the subreddit is private)"
|
|
247
|
+
if self.auth == "oauth"
|
|
248
|
+
else "403 blocked (search feeds are blocked)"
|
|
249
|
+
)
|
|
250
|
+
self.feed_errors.append((url, why))
|
|
251
|
+
return None
|
|
252
|
+
if not resp.ok:
|
|
253
|
+
self.feed_errors.append((url, f"{resp.status_code} {resp.reason}"))
|
|
254
|
+
return None
|
|
255
|
+
return resp
|
|
256
|
+
return None
|
|
257
|
+
|
|
258
|
+
def _fetch_feed(self, url: str) -> list[dict]:
|
|
259
|
+
resp = self._get(url)
|
|
260
|
+
if resp is None:
|
|
261
|
+
return []
|
|
262
|
+
|
|
263
|
+
feed = feedparser.parse(resp.content)
|
|
264
|
+
entries = []
|
|
265
|
+
for entry in feed.entries[: self.limit_per_feed]:
|
|
266
|
+
entries.append(
|
|
267
|
+
{
|
|
268
|
+
"id": entry.get("id", ""),
|
|
269
|
+
"title": entry.get("title", ""),
|
|
270
|
+
"content": _clean_html(entry.get("summary", "")),
|
|
271
|
+
"author": entry.get("author", ""),
|
|
272
|
+
"url": entry.get("link", ""),
|
|
273
|
+
"published": entry.get("published", ""),
|
|
274
|
+
}
|
|
275
|
+
)
|
|
276
|
+
return entries
|
|
277
|
+
|
|
278
|
+
def _fetch_listing(self, subreddit: str) -> list[dict]:
|
|
279
|
+
"""One subreddit's newest posts over the authenticated JSON API.
|
|
280
|
+
|
|
281
|
+
Returns the same post dicts as `_fetch_feed`, and records failures the
|
|
282
|
+
same way, so everything downstream is transport-blind.
|
|
283
|
+
"""
|
|
284
|
+
url = _OAUTH_NEW_URL.format(sub=subreddit)
|
|
285
|
+
resp = self._get(url, params={"limit": self.limit_per_feed})
|
|
286
|
+
if resp is None:
|
|
287
|
+
return []
|
|
288
|
+
try:
|
|
289
|
+
payload = resp.json()
|
|
290
|
+
except ValueError as exc:
|
|
291
|
+
self.feed_errors.append((url, f"reply was not JSON: {exc}"))
|
|
292
|
+
return []
|
|
293
|
+
|
|
294
|
+
# A 2xx carrying something that is not a listing is a failed feed, not
|
|
295
|
+
# an empty one. Without this, `{}` reads as "no new posts" and counts
|
|
296
|
+
# toward a healthy run -- so every feed could answer that way and the
|
|
297
|
+
# all-failed raise would never fire. A JSON array, meanwhile, used to
|
|
298
|
+
# raise AttributeError straight out of fetch(), losing the posts other
|
|
299
|
+
# feeds had already returned.
|
|
300
|
+
data = payload.get("data") if isinstance(payload, dict) else None
|
|
301
|
+
children = data.get("children") if isinstance(data, dict) else None
|
|
302
|
+
if not isinstance(children, list):
|
|
303
|
+
self.feed_errors.append(
|
|
304
|
+
(url, "reply was not a listing (no 'data.children' list)")
|
|
305
|
+
)
|
|
306
|
+
return []
|
|
307
|
+
|
|
308
|
+
entries = []
|
|
309
|
+
malformed = 0
|
|
310
|
+
for child in children[: self.limit_per_feed]:
|
|
311
|
+
post = child.get("data") if isinstance(child, dict) else None
|
|
312
|
+
if not isinstance(post, dict):
|
|
313
|
+
# One bad row must not lose the good rows beside it.
|
|
314
|
+
malformed += 1
|
|
315
|
+
continue
|
|
316
|
+
permalink = str(post.get("permalink") or "")
|
|
317
|
+
entries.append(
|
|
318
|
+
{
|
|
319
|
+
# `name` is the fullname ("t3_1abcde") that Reddit's own
|
|
320
|
+
# Atom feed puts in <id>, and so is what the dedupe state
|
|
321
|
+
# has been keyed on all along: 12453 of the 12497 ids in
|
|
322
|
+
# the deployment's state are exactly that shape. Keying on
|
|
323
|
+
# anything else here — the permalink, say — would make
|
|
324
|
+
# every post ever seen look new, and the first
|
|
325
|
+
# authenticated run would re-send years of leads to every
|
|
326
|
+
# destination at once.
|
|
327
|
+
"id": str(post.get("name") or ""),
|
|
328
|
+
"title": str(post.get("title") or ""),
|
|
329
|
+
# selftext is Markdown, not HTML, so it needs no _clean_html.
|
|
330
|
+
"content": str(post.get("selftext") or ""),
|
|
331
|
+
"author": str(post.get("author") or ""),
|
|
332
|
+
"url": (
|
|
333
|
+
f"https://www.reddit.com{permalink}"
|
|
334
|
+
if permalink
|
|
335
|
+
else str(post.get("url") or "")
|
|
336
|
+
),
|
|
337
|
+
"published": _iso(post.get("created_utc")),
|
|
338
|
+
}
|
|
339
|
+
)
|
|
340
|
+
if malformed:
|
|
341
|
+
print(
|
|
342
|
+
f"reddit source: r/{subreddit} returned {malformed} unreadable "
|
|
343
|
+
f"entry/entries, which are missing from this run",
|
|
344
|
+
file=sys.stderr,
|
|
345
|
+
)
|
|
346
|
+
retval = entries
|
|
347
|
+
return retval
|
|
348
|
+
|
|
349
|
+
def _to_signal(self, post: dict, subreddit: str) -> Signal:
|
|
350
|
+
title = post.get("title", "")
|
|
351
|
+
content = post.get("content", "")
|
|
352
|
+
retval = Signal(
|
|
353
|
+
# Reddit's RSS id is already stable and globally unique; fall back to
|
|
354
|
+
# the permalink so a feed without ids still dedupes sanely.
|
|
355
|
+
id=post.get("id") or post.get("url", ""),
|
|
356
|
+
text=f"{title}\n\n{content}".strip(),
|
|
357
|
+
url=post.get("url", ""),
|
|
358
|
+
source="reddit",
|
|
359
|
+
meta={
|
|
360
|
+
"title": title,
|
|
361
|
+
"author": post.get("author", ""),
|
|
362
|
+
"published": post.get("published", ""),
|
|
363
|
+
"subreddit": _extract_subreddit(post.get("url", "")) or subreddit,
|
|
364
|
+
},
|
|
365
|
+
)
|
|
366
|
+
return retval
|
|
367
|
+
|
|
368
|
+
def _rules_for(self, subreddit: str, cfg: dict) -> str:
|
|
369
|
+
"""The rules text to attach to this subreddit's signals ("" for none).
|
|
370
|
+
|
|
371
|
+
Hand-kept `rules` in the subreddit's config win and are used verbatim,
|
|
372
|
+
with no request: since about 2026-10 Reddit 403s every unauthenticated
|
|
373
|
+
JSON endpoint, rules.json included, while the RSS feeds still work
|
|
374
|
+
(issue #105). Without them, and with `include_rules` on, the rules are
|
|
375
|
+
fetched; a fetch that fails attaches _RULES_UNREADABLE rather than
|
|
376
|
+
nothing, because a draft that sees no rule includes the promotional
|
|
377
|
+
line, and a rule we could not read is not a rule that allows it.
|
|
378
|
+
"""
|
|
379
|
+
configured = cfg.get("rules")
|
|
380
|
+
if isinstance(configured, str) and configured.strip():
|
|
381
|
+
return configured.strip()
|
|
382
|
+
if not self.include_rules:
|
|
383
|
+
return ""
|
|
384
|
+
fetched = self._fetch_rules(subreddit)
|
|
385
|
+
if fetched is None:
|
|
386
|
+
retval = _RULES_UNREADABLE.format(why=self.rule_errors[-1][1])
|
|
387
|
+
return retval
|
|
388
|
+
return fetched
|
|
389
|
+
|
|
390
|
+
def _fetch_rules(self, subreddit: str) -> str | None:
|
|
391
|
+
"""One subreddit's self-promotion rules, or None if they cannot be read.
|
|
392
|
+
|
|
393
|
+
Deliberately NOT a run-failing error, unlike a failed feed. A feed that
|
|
394
|
+
fails means no leads; rules that fail to load mean a degraded lead
|
|
395
|
+
rather than a missing one. The failure is recorded in `rule_errors`.
|
|
396
|
+
|
|
397
|
+
Under `auth: "oauth"` this reads `oauth.reddit.com/r/<sub>/about/rules`,
|
|
398
|
+
which is the whole reason the 403 on the unauthenticated endpoint stops
|
|
399
|
+
mattering.
|
|
400
|
+
"""
|
|
401
|
+
url = (_OAUTH_RULES_URL if self.auth == "oauth" else _RULES_URL).format(sub=subreddit)
|
|
402
|
+
try:
|
|
403
|
+
resp = requests.get(url, headers=self._headers(), timeout=self.timeout)
|
|
404
|
+
except requests.RequestException as exc:
|
|
405
|
+
self.rule_errors.append((subreddit, f"{type(exc).__name__}: {exc}"))
|
|
406
|
+
return None
|
|
407
|
+
if not resp.ok:
|
|
408
|
+
self.rule_errors.append((subreddit, f"{resp.status_code} {resp.reason}"))
|
|
409
|
+
return None
|
|
410
|
+
try:
|
|
411
|
+
payload = resp.json()
|
|
412
|
+
except ValueError as exc:
|
|
413
|
+
self.rule_errors.append((subreddit, f"reply was not JSON: {exc}"))
|
|
414
|
+
return None
|
|
415
|
+
retval = _promo_rules(payload)
|
|
416
|
+
return retval
|
|
417
|
+
|
|
418
|
+
def fetch(self) -> list[Signal]:
|
|
419
|
+
self.feed_errors = []
|
|
420
|
+
self.feed_counts = []
|
|
421
|
+
self.rule_errors = []
|
|
422
|
+
signals: list[Signal] = []
|
|
423
|
+
seen_ids: set[str] = set()
|
|
424
|
+
attempted = 0
|
|
425
|
+
|
|
426
|
+
rules_by_sub: dict[str, str] = {}
|
|
427
|
+
|
|
428
|
+
for subreddit, cfg in self.subreddits.items():
|
|
429
|
+
rules_by_sub[subreddit] = self._rules_for(subreddit, cfg or {})
|
|
430
|
+
searches = (cfg or {}).get("searches") or []
|
|
431
|
+
if self.auth == "oauth":
|
|
432
|
+
urls = [_OAUTH_NEW_URL.format(sub=subreddit)]
|
|
433
|
+
else:
|
|
434
|
+
urls = [_search_url(subreddit, s) for s in searches] or [_new_url(subreddit)]
|
|
435
|
+
for url in urls:
|
|
436
|
+
attempted += 1
|
|
437
|
+
# `_fetch_feed` returns [] both for a feed that failed and for
|
|
438
|
+
# one that is genuinely empty, and those are opposite facts.
|
|
439
|
+
# The error list growing across the call is what separates
|
|
440
|
+
# them, so a feed counted here is one that actually answered.
|
|
441
|
+
failures_before = len(self.feed_errors)
|
|
442
|
+
posts = (
|
|
443
|
+
self._fetch_listing(subreddit)
|
|
444
|
+
if self.auth == "oauth"
|
|
445
|
+
else self._fetch_feed(url)
|
|
446
|
+
)
|
|
447
|
+
if len(self.feed_errors) == failures_before:
|
|
448
|
+
self.feed_counts.append((subreddit, url, len(posts)))
|
|
449
|
+
for post in posts:
|
|
450
|
+
signal = self._to_signal(post, subreddit)
|
|
451
|
+
# The same post can surface under several search terms.
|
|
452
|
+
if not signal.id or signal.id in seen_ids:
|
|
453
|
+
continue
|
|
454
|
+
seen_ids.add(signal.id)
|
|
455
|
+
rules = rules_by_sub.get(subreddit)
|
|
456
|
+
if rules:
|
|
457
|
+
signal.meta["subreddit_rules"] = rules
|
|
458
|
+
signals.append(signal)
|
|
459
|
+
|
|
460
|
+
# Neither must a half-failed one. Until this line existed, a feed that
|
|
461
|
+
# 404ed or stayed rate-limited was recorded in `feed_errors` and then
|
|
462
|
+
# never mentioned again unless *every* feed failed, so the usual case
|
|
463
|
+
# -- some feeds through, some not -- was silent. It is not a rare case:
|
|
464
|
+
# across 285 runs of the leads agent the fetched count never once
|
|
465
|
+
# reached the configured 8 x 25, and its three most common values sat
|
|
466
|
+
# one, two and three whole feeds short. Roughly 40% of the configured
|
|
467
|
+
# supply had been going missing since the agent was first deployed,
|
|
468
|
+
# with nothing in any log to say so.
|
|
469
|
+
if attempted:
|
|
470
|
+
got = sum(n for _, _, n in self.feed_counts)
|
|
471
|
+
per_sub: dict[str, int] = {}
|
|
472
|
+
for subreddit, _, n in self.feed_counts:
|
|
473
|
+
per_sub[subreddit] = per_sub.get(subreddit, 0) + n
|
|
474
|
+
detail = " ".join(f"{sub}={n}" for sub, n in per_sub.items())
|
|
475
|
+
print(
|
|
476
|
+
f"reddit source: {len(self.feed_counts)}/{attempted} feed(s) answered "
|
|
477
|
+
f"with {got} post(s) — {detail or 'none'}",
|
|
478
|
+
file=sys.stderr,
|
|
479
|
+
)
|
|
480
|
+
# Unconditional on feed_errors, including the all-failed case below:
|
|
481
|
+
# the raise quotes only the first three, and the reason the other five
|
|
482
|
+
# failed is worth having.
|
|
483
|
+
if self.feed_errors:
|
|
484
|
+
print(
|
|
485
|
+
f"reddit source: {len(self.feed_errors)} of {attempted} feed(s) failed and "
|
|
486
|
+
f"their posts are missing from this run — "
|
|
487
|
+
f"{'; '.join(f'{url}: {why}' for url, why in self.feed_errors)}",
|
|
488
|
+
file=sys.stderr,
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
# A totally failed run must not masquerade as a quiet one.
|
|
492
|
+
if attempted and len(self.feed_errors) == attempted:
|
|
493
|
+
detail = "; ".join(f"{url}: {why}" for url, why in self.feed_errors[:3])
|
|
494
|
+
raise RuntimeError(f"reddit source: all {attempted} feed(s) failed — {detail}")
|
|
495
|
+
if self.rule_errors:
|
|
496
|
+
print(
|
|
497
|
+
f"reddit source: rules unreadable for {len(self.rule_errors)} subreddit(s), "
|
|
498
|
+
f"their leads treat self-promotion as forbidden — "
|
|
499
|
+
f"{'; '.join(f'{sub}: {why}' for sub, why in self.rule_errors)}",
|
|
500
|
+
file=sys.stderr,
|
|
501
|
+
)
|
|
502
|
+
|
|
503
|
+
retval = signals
|
|
504
|
+
return retval
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
_RULES_URL = "https://www.reddit.com/r/{sub}/about/rules.json"
|
|
508
|
+
_OAUTH_TOKEN_URL = "https://www.reddit.com/api/v1/access_token"
|
|
509
|
+
_OAUTH_NEW_URL = "https://oauth.reddit.com/r/{sub}/new"
|
|
510
|
+
_OAUTH_RULES_URL = "https://oauth.reddit.com/r/{sub}/about/rules"
|
|
511
|
+
_RULES_UNREADABLE = (
|
|
512
|
+
"This subreddit's rules could not be read ({why}). Treat self-promotion as "
|
|
513
|
+
"forbidden here: no line about who we are, no offer."
|
|
514
|
+
)
|
|
515
|
+
# Rule text that bears on whether we may mention ourselves at all. Matching on
|
|
516
|
+
# the rule's own words rather than its number, because numbering differs per
|
|
517
|
+
# subreddit and the relevant rule is rarely rule 1.
|
|
518
|
+
_PROMO_WORDS = ("promot", "advertis", "solicit", "spam", "self-post", "selfpromo", "referral", "vendor")
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _promo_rules(payload: dict) -> str:
|
|
522
|
+
"""The self-promotion rules from an `about/rules` payload, as text.
|
|
523
|
+
|
|
524
|
+
The draft that goes under a lead has to obey the community's own rule rather
|
|
525
|
+
than a generalisation about what communities usually allow. Both transports
|
|
526
|
+
return the same payload shape, so this parses either.
|
|
527
|
+
|
|
528
|
+
Returns every rule whose title or description mentions promotion; if none
|
|
529
|
+
match, the short titles of all of them, because "this subreddit has rules and
|
|
530
|
+
none of them obviously covers this" is still better than silence for a human
|
|
531
|
+
about to post.
|
|
532
|
+
"""
|
|
533
|
+
rules = payload.get("rules") or []
|
|
534
|
+
hits, titles = [], []
|
|
535
|
+
for rule in rules:
|
|
536
|
+
if not isinstance(rule, dict):
|
|
537
|
+
continue
|
|
538
|
+
short = str(rule.get("short_name") or "").strip()
|
|
539
|
+
desc = str(rule.get("description") or "").strip()
|
|
540
|
+
titles.append(short)
|
|
541
|
+
haystack = f"{short} {desc}".lower()
|
|
542
|
+
if any(word in haystack for word in _PROMO_WORDS):
|
|
543
|
+
hits.append(f"{short}: {desc}" if desc else short)
|
|
544
|
+
if hits:
|
|
545
|
+
retval = "\n".join(hits)
|
|
546
|
+
return retval
|
|
547
|
+
retval = ("no rule mentions promotion; all rules: " + "; ".join(t for t in titles if t)) if titles else ""
|
|
548
|
+
return retval
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _normalize_subreddits(declared: object) -> dict[str, dict]:
|
|
552
|
+
"""Accept either the plain list form or the mapping form.
|
|
553
|
+
|
|
554
|
+
subreddits: [construction, smallbusiness]
|
|
555
|
+
|
|
556
|
+
subreddits:
|
|
557
|
+
construction:
|
|
558
|
+
searches: [paperwork, invoicing]
|
|
559
|
+
smallbusiness:
|
|
560
|
+
rules: "No self-promotion: ..." # hand-kept, attached verbatim
|
|
561
|
+
|
|
562
|
+
The list form fetches /new.rss, which is the reliable path now that search
|
|
563
|
+
feeds 403.
|
|
564
|
+
"""
|
|
565
|
+
if isinstance(declared, dict):
|
|
566
|
+
retval = {name: (cfg or {}) for name, cfg in declared.items()}
|
|
567
|
+
elif isinstance(declared, list):
|
|
568
|
+
retval = {name: {} for name in declared}
|
|
569
|
+
else:
|
|
570
|
+
retval = {}
|
|
571
|
+
return retval
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def _credentials(cfg: dict, subreddits: dict[str, dict]) -> tuple[str, str]:
|
|
575
|
+
"""The OAuth client id and secret, from the environment variables cfg names.
|
|
576
|
+
|
|
577
|
+
Raises rather than returning blanks: see the note on silent fallback in the
|
|
578
|
+
module docstring. The values themselves never appear in config, in a log or
|
|
579
|
+
in an error message — only the names of the variables that should hold them.
|
|
580
|
+
"""
|
|
581
|
+
declared_searches = [name for name, sub in subreddits.items() if (sub or {}).get("searches")]
|
|
582
|
+
if declared_searches:
|
|
583
|
+
raise RuntimeError(
|
|
584
|
+
"reddit source: 'searches' is not supported with auth 'oauth' "
|
|
585
|
+
f"(declared for {', '.join(declared_searches)}). Drop them, or use the RSS transport."
|
|
586
|
+
)
|
|
587
|
+
id_env = str(cfg.get("client_id_env", "REDDIT_CLIENT_ID"))
|
|
588
|
+
secret_env = str(cfg.get("client_secret_env", "REDDIT_CLIENT_SECRET"))
|
|
589
|
+
client_id = os.environ.get(id_env, "").strip()
|
|
590
|
+
client_secret = os.environ.get(secret_env, "").strip()
|
|
591
|
+
missing = [
|
|
592
|
+
name for name, value in ((id_env, client_id), (secret_env, client_secret)) if not value
|
|
593
|
+
]
|
|
594
|
+
if missing:
|
|
595
|
+
raise RuntimeError(
|
|
596
|
+
f"reddit source: auth 'oauth' needs {' and '.join(missing)} in the environment. "
|
|
597
|
+
"Not falling back to the public RSS feeds: that is the outage this transport "
|
|
598
|
+
"exists to escape, and a quiet fallback would hide a credential problem inside it."
|
|
599
|
+
)
|
|
600
|
+
retval = (client_id, client_secret)
|
|
601
|
+
return retval
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
@register_source("reddit")
|
|
605
|
+
def build(cfg: dict) -> Source:
|
|
606
|
+
subreddits = _normalize_subreddits(cfg.get("subreddits"))
|
|
607
|
+
if not subreddits:
|
|
608
|
+
raise RuntimeError("reddit source needs a non-empty 'subreddits' list or mapping")
|
|
609
|
+
auth = (str(cfg.get("auth") or "none")).strip().lower()
|
|
610
|
+
if auth not in ("none", "oauth"):
|
|
611
|
+
raise RuntimeError(f"reddit source: unknown auth {auth!r} (expected 'none' or 'oauth')")
|
|
612
|
+
client_id, client_secret = _credentials(cfg, subreddits) if auth == "oauth" else ("", "")
|
|
613
|
+
retval = RedditSource(
|
|
614
|
+
subreddits=subreddits,
|
|
615
|
+
user_agent=cfg.get("user_agent", _DEFAULT_USER_AGENT),
|
|
616
|
+
delay_seconds=float(cfg.get("delay_seconds", 2.0)),
|
|
617
|
+
timeout=int(cfg.get("timeout", 15)),
|
|
618
|
+
limit_per_feed=int(cfg.get("limit_per_feed", 25)),
|
|
619
|
+
max_retries=int(cfg.get("max_retries", 2)),
|
|
620
|
+
include_rules=bool(cfg.get("include_rules", False)),
|
|
621
|
+
auth=auth,
|
|
622
|
+
client_id=client_id,
|
|
623
|
+
client_secret=client_secret,
|
|
624
|
+
)
|
|
625
|
+
return retval
|