Skip to content

Instantly share code, notes, and snippets.

@aescarcha
Created November 10, 2026 17:05
Show Gist options
  • Select an option

  • Save aescarcha/3c2e01f3ada696673d32ab9de4e05aa0 to your computer and use it in GitHub Desktop.

Select an option

Save aescarcha/3c2e01f3ada696673d32ab9de4e05aa0 to your computer and use it in GitHub Desktop.
reddit_fetch.py: read-only Reddit reader for a solo iOS developer's personal review queue (never posts, comments, votes or messages)
#!/usr/bin/env python3
"""
Read-only Reddit fetcher for the promo scan (skill: reddit-promo).
Uses the logged-in cookie session from app-store-research/.env.local
(REDDIT_COOKIE + REDDIT_USER_AGENT, read with a regex — never `source`d, never
printed). Honours Reddit's per-window budget (~100 requests): waits for
x-ratelimit-reset when remaining < 3 or on HTTP 429, retries one network error.
reddit_fetch.py thread <post url> [<post url> ...] [--comments 15] # post + top comments, 1 request each
reddit_fetch.py comments <post url or /r/x/comments/id/...> [--limit 15] # tone read only
reddit_fetch.py search --subs foraging,mycology --q '"foraging app" OR "log my finds"' [--t week] [--limit 50]
reddit_fetch.py new --sub iosapps [--limit 100] [--app-links]
Since 2026-11-04 Reddit answers search.json and the new/hot listings with an HTML
block page (403) for this session, while single threads still load. Discovery
therefore runs through web search (Parallel), and `thread` reads each candidate
it finds. `search`/`new` stay for the day API access is approved.
Output: JSON lines on stdout, one post/comment per line (`thread`: one object per post).
"""
from __future__ import annotations
import argparse
import json
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
HERE = Path(__file__).resolve().parent
ENV_FILE = HERE.parents[2] / ".env.local" # app-store-research/.env.local
BASE = "https://www.reddit.com"
APP_LINK_RE = re.compile(r"apps\.apple\.com/[a-z-]*/?app/[^\s/)]*/?id(\d+)")
THREAD_RE = re.compile(r"(?:reddit\.com)?((?:/r/[A-Za-z0-9_]+)?/comments/[a-z0-9]+)", re.I)
def thread_path(url: str) -> str | None:
"""/r/<sub>/comments/<id> from any thread URL a search engine returns
(?sort=new, ?rdt=..., old./np./www. hosts, trailing slug). None for listings
and /s/ share links, which only resolve through a redirect."""
m = THREAD_RE.search(url)
return m.group(1) if m else None
def load_session(env_file: Path = ENV_FILE) -> dict[str, str]:
"""{cookie, ua} from .env.local. Values may be quoted and contain ';' and spaces."""
if not env_file.exists():
raise SystemExit(f"{env_file} not found (needs REDDIT_COOKIE and REDDIT_USER_AGENT)")
text = env_file.read_text(encoding="utf-8")
out = {}
for key, name in (("REDDIT_COOKIE", "cookie"), ("REDDIT_USER_AGENT", "ua")):
m = re.search(rf"^{key}=(.*)$", text, re.M)
if not m:
raise SystemExit(f"{key} missing from {env_file.name}")
out[name] = m.group(1).strip().strip('"').strip("'")
return out
class Reddit:
def __init__(self, session: dict[str, str], opener=urllib.request.urlopen, sleep=time.sleep, log=None):
self.session, self.opener, self.sleep = session, opener, sleep
self.log = log or (lambda m: print(m, file=sys.stderr))
self.remaining = None
self.requests = 0
def get(self, path: str, params: dict | None = None) -> dict | list:
url = path if path.startswith("http") else BASE + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
req = urllib.request.Request(url, headers={"Cookie": self.session["cookie"],
"User-Agent": self.session["ua"]})
for attempt in range(4):
try:
with self.opener(req, timeout=30) as res:
self.requests += 1
self._budget(res.headers)
return json.loads(res.read().decode("utf-8"))
except urllib.error.HTTPError as e:
self.requests += 1
if e.code == 429 and attempt < 3:
wait = float(e.headers.get("x-ratelimit-reset") or 30) + 1
self.log(f"429 — waiting {wait:.0f}s for the rate-limit window")
self.sleep(wait)
continue
if e.code == 403 and (e.read(1) or b"").startswith(b"<"):
raise SystemExit(f"Reddit HTTP 403 for {path}: an HTML block page, not an auth error. "
"Reddit refuses this endpoint for scripted access (listings and search "
"since 2026-11-04); the session can still be valid. Do not work around it.")
raise SystemExit(f"Reddit HTTP {e.code} for {path}. A JSON 403 on /api/me.json too means "
"the cookie expired")
except (urllib.error.URLError, TimeoutError, ConnectionResetError) as e:
if attempt == 0:
self.log(f"network error ({e}); retrying once")
self.sleep(2)
continue
raise SystemExit(f"network error for {path}: {e}")
raise SystemExit(f"gave up on {path}")
def _budget(self, headers) -> None:
rem = headers.get("x-ratelimit-remaining")
if rem is None:
return
self.remaining = float(rem)
if self.remaining < 3:
wait = float(headers.get("x-ratelimit-reset") or 30) + 1
self.log(f"rate budget nearly spent ({rem} left) — waiting {wait:.0f}s")
self.sleep(wait)
def post_row(d: dict) -> dict:
text = d.get("selftext") or ""
ids = APP_LINK_RE.findall(text + " " + (d.get("url") or ""))
return {
"url": BASE + d.get("permalink", ""),
"subreddit": d.get("subreddit"),
"title": d.get("title"),
"author": d.get("author"),
"flair": d.get("link_flair_text"),
"score": d.get("score"),
"num_comments": d.get("num_comments"),
"age_hours": round((time.time() - d.get("created_utc", time.time())) / 3600, 1),
"selftext": text[:1500],
"app_store_ids": sorted(set(ids)),
}
def search(r: Reddit, subs: list[str], q: str, t: str = "week", limit: int = 50) -> list[dict]:
data = r.get(f"/r/{'+'.join(subs)}/search.json",
{"q": q, "restrict_sr": 1, "sort": "new", "t": t, "limit": limit})
return [post_row(c["data"]) for c in data.get("data", {}).get("children", [])]
def new(r: Reddit, sub: str, limit: int = 100, app_links: bool = False) -> list[dict]:
data = r.get(f"/r/{sub}/new.json", {"limit": limit})
rows = [post_row(c["data"]) for c in data.get("data", {}).get("children", [])]
return [x for x in rows if x["app_store_ids"]] if app_links else rows
def _top_comments(data, limit: int) -> list[dict]:
out = []
for c in (data[1]["data"]["children"] if isinstance(data, list) and len(data) > 1 else []):
if c.get("kind") != "t1":
continue
d = c["data"]
out.append({"score": d.get("score"), "author": d.get("author"),
"words": len((d.get("body") or "").split()),
"body": (d.get("body") or "").replace("\n", " ")[:300]})
return sorted(out, key=lambda x: -(x["score"] or 0))[:limit]
def comments(r: Reddit, post: str, limit: int = 15) -> list[dict]:
path = thread_path(post) or (urllib.parse.urlparse(post).path if post.startswith("http") else post)
return _top_comments(r.get(path.rstrip("/") + ".json", {"limit": 50, "sort": "top"}), limit)
def thread(r: Reddit, url: str, n_comments: int = 15) -> dict | None:
"""The post (with its real age) and its top comments, from one request.
None when the URL is not a thread or the post is gone."""
path = thread_path(url)
if not path:
return None
data = r.get(path + ".json", {"limit": 50, "sort": "top"})
kids = data[0]["data"]["children"] if isinstance(data, list) and data else []
if not kids:
return None
d = kids[0]["data"]
if d.get("removed_by_category") or d.get("selftext") in ("[removed]", "[deleted]"):
return None
row = post_row(d)
row["comments"] = _top_comments(data, n_comments)
return row
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("search"); s.add_argument("--subs", required=True); s.add_argument("--q", required=True)
s.add_argument("--t", default="week"); s.add_argument("--limit", type=int, default=50)
n = sub.add_parser("new"); n.add_argument("--sub", required=True); n.add_argument("--limit", type=int, default=100)
n.add_argument("--app-links", action="store_true")
c = sub.add_parser("comments"); c.add_argument("post"); c.add_argument("--limit", type=int, default=15)
t = sub.add_parser("thread"); t.add_argument("urls", nargs="+"); t.add_argument("--comments", type=int, default=15)
a = ap.parse_args(argv)
r = Reddit(load_session())
if a.cmd == "thread":
seen, rows = set(), []
for u in a.urls:
p = thread_path(u)
if not p or p.lower() in seen:
print(f"# skip (not a thread or duplicate): {u}", file=sys.stderr)
continue
seen.add(p.lower())
row = thread(r, u, a.comments)
if row is None:
print(f"# skip (removed or empty): {u}", file=sys.stderr)
else:
rows.append(row)
elif a.cmd == "search":
rows = search(r, [x.strip() for x in a.subs.split(",") if x.strip()], a.q, a.t, a.limit)
elif a.cmd == "new":
rows = new(r, a.sub, a.limit, a.app_links)
else:
rows = comments(r, a.post, a.limit)
for row in rows:
print(json.dumps(row, ensure_ascii=False))
print(f"# {len(rows)} rows, {r.requests} request(s), budget left: {r.remaining}", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment