Skip to content

Commit 0adaf1c

Browse files
committed
switch to use reddit cookies
1 parent b0b441f commit 0adaf1c

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
# Custom
77
.DS_Store
8+
reddit_cookies.json
89
scripts/*.txt
910
all-technologies.json
1011
chat*.json

scripts/reddit_top.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,10 @@
66
"""
77

88
import json
9+
import requests
910
import sys
1011
from pathlib import Path
11-
from urllib.request import Request, urlopen
12+
from urllib.parse import urlparse
1213

1314
from utils import MIN_REDDIT_POINTS, TOP_REDDIT_LIMIT, USER_AGENT, create_slug
1415

@@ -35,13 +36,22 @@
3536

3637
# SUBREDDITS = ["r/dotnet", "r/csharp"]
3738

39+
REDDIT_COOKIES = json.loads(Path(__file__).parent.joinpath("reddit_cookies.json").read_text())
40+
41+
def create_cookie_jar():
42+
parsed = urlparse("https://www.reddit.com")
43+
jar = requests.cookies.RequestsCookieJar()
44+
for name, value in REDDIT_COOKIES.items():
45+
jar.set(name, value, domain=parsed.hostname, path="/")
46+
return jar
3847

3948
def fetch_subreddit_posts(subreddit: str, limit: int = 50) -> list[dict]:
4049
"""Fetch top posts from a subreddit using Reddit's JSON API."""
4150
url = f"https://www.reddit.com/{subreddit}/hot.json?limit={limit}"
42-
req = Request(url, headers={"User-Agent": USER_AGENT})
43-
with urlopen(req, timeout=10) as resp:
44-
data = json.loads(resp.read().decode("utf-8"))
51+
resp = requests.get(url, headers={"user-agent": USER_AGENT},
52+
cookies=create_cookie_jar(), timeout=30, allow_redirects=True)
53+
resp.raise_for_status()
54+
data = resp.json()
4555

4656
posts = []
4757
for child in data.get("data", {}).get("children", []):

0 commit comments

Comments
 (0)