@auscera/socialscrape 0.0.0-stage → 2.0.2
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/README.md +111 -2
- package/bin/socialscrape.mjs +115 -0
- package/engine/README.md +245 -0
- package/engine/SKILL.md +194 -0
- package/engine/agent.py +665 -0
- package/engine/batch_manager.py +622 -0
- package/engine/cli.py +23 -0
- package/engine/handlers.py +1109 -0
- package/engine/plugins/__init__.py +77 -0
- package/engine/plugins/instagram-scrape/README.md +164 -0
- package/engine/plugins/instagram-scrape/SKILL.md +53 -0
- package/engine/plugins/instagram-scrape/cli.py +176 -0
- package/engine/plugins/instagram-scrape/core.py +408 -0
- package/engine/plugins/instagram-scrape/plugin.json +42 -0
- package/engine/plugins/linkedin-scrape/README.md +143 -0
- package/engine/plugins/linkedin-scrape/SKILL.md +47 -0
- package/engine/plugins/linkedin-scrape/cli.py +126 -0
- package/engine/plugins/linkedin-scrape/core.py +188 -0
- package/engine/plugins/linkedin-scrape/plugin.json +36 -0
- package/engine/plugins/meta-ad-library-scraper/README.md +127 -0
- package/engine/plugins/meta-ad-library-scraper/SKILL.md +44 -0
- package/engine/plugins/meta-ad-library-scraper/cli.py +161 -0
- package/engine/plugins/meta-ad-library-scraper/core.py +348 -0
- package/engine/plugins/meta-ad-library-scraper/plugin.json +44 -0
- package/engine/plugins/pinterest-scraper/README.md +150 -0
- package/engine/plugins/pinterest-scraper/SKILL.md +45 -0
- package/engine/plugins/pinterest-scraper/cli.py +193 -0
- package/engine/plugins/pinterest-scraper/core.py +420 -0
- package/engine/plugins/pinterest-scraper/plugin.json +40 -0
- package/engine/plugins/reddit-discussion-scraper/README.md +162 -0
- package/engine/plugins/reddit-discussion-scraper/SKILL.md +52 -0
- package/engine/plugins/reddit-discussion-scraper/cli.py +218 -0
- package/engine/plugins/reddit-discussion-scraper/core.py +546 -0
- package/engine/plugins/reddit-discussion-scraper/plugin.json +46 -0
- package/engine/plugins/shared/__init__.py +15 -0
- package/engine/plugins/shared/paths.py +90 -0
- package/engine/plugins/shared/process_runner.py +169 -0
- package/engine/plugins/shared/session_manager.py +287 -0
- package/engine/plugins/threads-scraper/README.md +139 -0
- package/engine/plugins/threads-scraper/SKILL.md +43 -0
- package/engine/plugins/threads-scraper/cli.py +178 -0
- package/engine/plugins/threads-scraper/core.py +460 -0
- package/engine/plugins/threads-scraper/plugin.json +40 -0
- package/engine/plugins/tiktok-scrape/README.md +158 -0
- package/engine/plugins/tiktok-scrape/SKILL.md +51 -0
- package/engine/plugins/tiktok-scrape/cli.py +163 -0
- package/engine/plugins/tiktok-scrape/core.py +313 -0
- package/engine/plugins/tiktok-scrape/plugin.json +40 -0
- package/engine/plugins/twitter-scrape/README.md +158 -0
- package/engine/plugins/twitter-scrape/SKILL.md +50 -0
- package/engine/plugins/twitter-scrape/cli.py +153 -0
- package/engine/plugins/twitter-scrape/core.py +254 -0
- package/engine/plugins/twitter-scrape/plugin.json +40 -0
- package/engine/plugins/youtube-scrape/README.md +199 -0
- package/engine/plugins/youtube-scrape/SKILL.md +115 -0
- package/engine/plugins/youtube-scrape/cli.py +340 -0
- package/engine/plugins/youtube-scrape/core.py +829 -0
- package/engine/plugins/youtube-scrape/plugin.json +48 -0
- package/engine/requirements.txt +8 -0
- package/engine/socialscrape_cli.py +500 -0
- package/engine/storage.py +570 -0
- package/engine/ui.py +690 -0
- package/package.json +27 -3
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Reddit Discussion Scraper Pure SDK (`core.py`)
|
|
3
|
+
Pure zero-side-effect Python SDK for Reddit discussion extraction, nested comment trees, and media downloading.
|
|
4
|
+
Utilizes Reddit's unauthenticated .json endpoint trick with custom User-Agent headers.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
import time
|
|
12
|
+
import random
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Dict, List, Any, Optional, Union
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
import requests
|
|
18
|
+
HAS_REQUESTS = True
|
|
19
|
+
except ImportError:
|
|
20
|
+
HAS_REQUESTS = False
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
import yt_dlp
|
|
24
|
+
HAS_YT_DLP = True
|
|
25
|
+
except ImportError:
|
|
26
|
+
HAS_YT_DLP = False
|
|
27
|
+
|
|
28
|
+
# Import shared SessionManager & Path Helpers
|
|
29
|
+
try:
|
|
30
|
+
from plugins.shared.session_manager import SessionManager, RateLimiter
|
|
31
|
+
from plugins.shared.paths import get_plugin_outputs_dir
|
|
32
|
+
HAS_SESSION_MANAGER = True
|
|
33
|
+
except ImportError:
|
|
34
|
+
_shared_parent = str(Path(__file__).parent.parent.resolve())
|
|
35
|
+
if _shared_parent not in sys.path:
|
|
36
|
+
sys.path.insert(0, _shared_parent)
|
|
37
|
+
from shared.paths import get_plugin_outputs_dir
|
|
38
|
+
try:
|
|
39
|
+
from shared.session_manager import SessionManager, RateLimiter
|
|
40
|
+
HAS_SESSION_MANAGER = True
|
|
41
|
+
except ImportError:
|
|
42
|
+
HAS_SESSION_MANAGER = False
|
|
43
|
+
|
|
44
|
+
PLUGIN_DIR = Path(__file__).parent.resolve()
|
|
45
|
+
DEFAULT_OUTPUTS_DIR = get_plugin_outputs_dir(PLUGIN_DIR)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _outputs_dir() -> Path:
|
|
49
|
+
return get_plugin_outputs_dir(PLUGIN_DIR)
|
|
50
|
+
|
|
51
|
+
USER_AGENTS = [
|
|
52
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
|
|
53
|
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
|
|
54
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0",
|
|
55
|
+
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def get_random_headers(session_cookie: Optional[str] = None) -> Dict[str, str]:
|
|
60
|
+
"""Generates stealth headers with a randomized modern User-Agent and optional burner session cookie."""
|
|
61
|
+
headers = {
|
|
62
|
+
"User-Agent": random.choice(USER_AGENTS),
|
|
63
|
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
|
64
|
+
"Accept-Language": "en-US,en;q=0.5",
|
|
65
|
+
"Connection": "keep-alive",
|
|
66
|
+
}
|
|
67
|
+
if session_cookie:
|
|
68
|
+
headers["Cookie"] = f"reddit_session={session_cookie}"
|
|
69
|
+
return headers
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def parse_reddit_target(target: str) -> Dict[str, str]:
|
|
73
|
+
"""
|
|
74
|
+
Parses a raw Reddit URL or input string into structured components.
|
|
75
|
+
Supported inputs:
|
|
76
|
+
- Subreddit: "r/sales", "sales", "https://reddit.com/r/sales"
|
|
77
|
+
- User: "u/spez", "user/spez", "https://reddit.com/user/spez"
|
|
78
|
+
- Post: "https://www.reddit.com/r/sales/comments/1abc23/how_to_close_deals/"
|
|
79
|
+
"""
|
|
80
|
+
t = target.strip()
|
|
81
|
+
|
|
82
|
+
# Check for full URL
|
|
83
|
+
if "reddit.com" in t or "redd.it" in t:
|
|
84
|
+
if "/comments/" in t:
|
|
85
|
+
match = re.search(r"/comments/([a-zA-Z0-9]+)", t)
|
|
86
|
+
post_id = match.group(1) if match else t
|
|
87
|
+
return {"type": "post", "id": post_id, "url": t}
|
|
88
|
+
elif "/user/" in t or "/u/" in t:
|
|
89
|
+
match = re.search(r"/(?:user|u)/([^/?#&]+)", t)
|
|
90
|
+
username = match.group(1) if match else t
|
|
91
|
+
return {"type": "user", "id": username, "url": t}
|
|
92
|
+
elif "/r/" in t:
|
|
93
|
+
match = re.search(r"/r/([^/?#&]+)", t)
|
|
94
|
+
subreddit = match.group(1) if match else t
|
|
95
|
+
return {"type": "subreddit", "id": subreddit, "url": t}
|
|
96
|
+
|
|
97
|
+
# Check for prefixes
|
|
98
|
+
if t.startswith("r/"):
|
|
99
|
+
return {"type": "subreddit", "id": t[2:], "url": f"https://www.reddit.com/{t}"}
|
|
100
|
+
if t.startswith("u/") or t.startswith("user/"):
|
|
101
|
+
username = t.split("/", 1)[1]
|
|
102
|
+
return {"type": "user", "id": username, "url": f"https://www.reddit.com/user/{username}"}
|
|
103
|
+
|
|
104
|
+
# Default to subreddit if no other hints
|
|
105
|
+
return {"type": "subreddit", "id": t, "url": f"https://www.reddit.com/r/{t}"}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _safe_json_get(url: str, params: Optional[Dict[str, Any]] = None, max_retries: int = 3) -> Optional[Any]:
|
|
109
|
+
"""Safely performs a GET request expecting JSON, handling rate limits with exponential backoff and session support."""
|
|
110
|
+
if not HAS_REQUESTS:
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
# Enforce rate limiter pacing if available
|
|
114
|
+
if HAS_SESSION_MANAGER:
|
|
115
|
+
try:
|
|
116
|
+
limiter = RateLimiter()
|
|
117
|
+
limiter.check_and_pace("reddit")
|
|
118
|
+
except Exception:
|
|
119
|
+
pass
|
|
120
|
+
|
|
121
|
+
# Retrieve burner cookie if stored
|
|
122
|
+
session_cookie = None
|
|
123
|
+
if HAS_SESSION_MANAGER:
|
|
124
|
+
try:
|
|
125
|
+
mgr = SessionManager()
|
|
126
|
+
session = mgr.get_session("reddit")
|
|
127
|
+
if session:
|
|
128
|
+
session_cookie = session.get("cookies", {}).get("reddit_session")
|
|
129
|
+
except Exception:
|
|
130
|
+
pass
|
|
131
|
+
|
|
132
|
+
# Route through old.reddit.com to maximize compatibility
|
|
133
|
+
url = url.replace("https://www.reddit.com", "https://old.reddit.com").replace("https://reddit.com", "https://old.reddit.com")
|
|
134
|
+
|
|
135
|
+
# Ensure URL ends with .json or has .json before query string
|
|
136
|
+
if "?" in url:
|
|
137
|
+
base, query = url.split("?", 1)
|
|
138
|
+
if not base.endswith(".json"):
|
|
139
|
+
url = f"{base}.json?{query}"
|
|
140
|
+
else:
|
|
141
|
+
if not url.endswith(".json"):
|
|
142
|
+
url = f"{url.rstrip('/')}.json"
|
|
143
|
+
|
|
144
|
+
for attempt in range(1, max_retries + 1):
|
|
145
|
+
try:
|
|
146
|
+
resp = requests.get(url, headers=get_random_headers(session_cookie=session_cookie), params=params, timeout=12)
|
|
147
|
+
if resp.status_code == 200:
|
|
148
|
+
try:
|
|
149
|
+
return resp.json()
|
|
150
|
+
except Exception:
|
|
151
|
+
return None
|
|
152
|
+
elif resp.status_code in (429, 500, 502, 503, 504):
|
|
153
|
+
time.sleep(min(2 ** attempt, 3))
|
|
154
|
+
continue
|
|
155
|
+
elif resp.status_code in (403, 404):
|
|
156
|
+
return None
|
|
157
|
+
except Exception:
|
|
158
|
+
if attempt < max_retries:
|
|
159
|
+
time.sleep(min(2 ** attempt, 3))
|
|
160
|
+
continue
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _parse_comment_tree(comment_node: Dict[str, Any], depth: int = 0, max_depth: int = 10) -> Optional[Dict[str, Any]]:
|
|
165
|
+
"""Recursively parses Reddit comment trees into a clean structured format."""
|
|
166
|
+
if depth > max_depth:
|
|
167
|
+
return None
|
|
168
|
+
|
|
169
|
+
kind = comment_node.get("kind")
|
|
170
|
+
data = comment_node.get("data", {})
|
|
171
|
+
|
|
172
|
+
if kind != "t1": # t1 represents a comment
|
|
173
|
+
return None
|
|
174
|
+
|
|
175
|
+
author = data.get("author", "[deleted]")
|
|
176
|
+
body = data.get("body", "")
|
|
177
|
+
score = data.get("score", 0)
|
|
178
|
+
created_utc = data.get("created_utc", 0)
|
|
179
|
+
comment_id = data.get("id", "")
|
|
180
|
+
permalink = f"https://reddit.com{data.get('permalink', '')}"
|
|
181
|
+
|
|
182
|
+
replies = []
|
|
183
|
+
replies_data = data.get("replies")
|
|
184
|
+
if isinstance(replies_data, dict):
|
|
185
|
+
children = replies_data.get("data", {}).get("children", [])
|
|
186
|
+
for child in children:
|
|
187
|
+
parsed_child = _parse_comment_tree(child, depth=depth + 1, max_depth=max_depth)
|
|
188
|
+
if parsed_child:
|
|
189
|
+
replies.append(parsed_child)
|
|
190
|
+
|
|
191
|
+
return {
|
|
192
|
+
"id": comment_id,
|
|
193
|
+
"author": author,
|
|
194
|
+
"body": body,
|
|
195
|
+
"score": score,
|
|
196
|
+
"created_utc": created_utc,
|
|
197
|
+
"depth": depth,
|
|
198
|
+
"permalink": permalink,
|
|
199
|
+
"replies_count": len(replies),
|
|
200
|
+
"replies": replies,
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def get_subreddit_posts(
|
|
205
|
+
subreddit: str,
|
|
206
|
+
sort: str = "hot",
|
|
207
|
+
time_filter: str = "all",
|
|
208
|
+
limit: int = 25,
|
|
209
|
+
output_dir: Optional[Union[Path, str]] = None
|
|
210
|
+
) -> Dict[str, Any]:
|
|
211
|
+
"""
|
|
212
|
+
Fetches top discussions from a subreddit.
|
|
213
|
+
Sort options: 'hot', 'new', 'top', 'rising'.
|
|
214
|
+
Time filter (for top): 'hour', 'day', 'week', 'month', 'year', 'all'.
|
|
215
|
+
"""
|
|
216
|
+
clean_sub = subreddit.replace("r/", "").strip("/")
|
|
217
|
+
url = f"https://www.reddit.com/r/{clean_sub}/{sort}.json"
|
|
218
|
+
params = {"limit": min(limit, 100)}
|
|
219
|
+
if sort == "top":
|
|
220
|
+
params["t"] = time_filter
|
|
221
|
+
|
|
222
|
+
data = _safe_json_get(url, params=params)
|
|
223
|
+
if not data or not isinstance(data, dict):
|
|
224
|
+
return {
|
|
225
|
+
"status": "error",
|
|
226
|
+
"subreddit": clean_sub,
|
|
227
|
+
"error": f"Failed to fetch posts from r/{clean_sub}. Subreddit may be private or banned.",
|
|
228
|
+
"posts": []
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
children = data.get("data", {}).get("children", [])
|
|
232
|
+
posts = []
|
|
233
|
+
for c in children:
|
|
234
|
+
p = c.get("data", {})
|
|
235
|
+
post_id = p.get("id")
|
|
236
|
+
title = p.get("title")
|
|
237
|
+
author = p.get("author")
|
|
238
|
+
selftext = p.get("selftext", "")
|
|
239
|
+
score = p.get("score", 0)
|
|
240
|
+
upvote_ratio = p.get("upvote_ratio", 0.0)
|
|
241
|
+
num_comments = p.get("num_comments", 0)
|
|
242
|
+
permalink = f"https://reddit.com{p.get('permalink', '')}"
|
|
243
|
+
created_utc = p.get("created_utc", 0)
|
|
244
|
+
is_video = p.get("is_video", False)
|
|
245
|
+
media_url = p.get("url_overridden_by_dest") or p.get("url")
|
|
246
|
+
|
|
247
|
+
posts.append({
|
|
248
|
+
"id": post_id,
|
|
249
|
+
"title": title,
|
|
250
|
+
"author": author,
|
|
251
|
+
"text": selftext,
|
|
252
|
+
"score": score,
|
|
253
|
+
"upvote_ratio": upvote_ratio,
|
|
254
|
+
"comments_count": num_comments,
|
|
255
|
+
"permalink": permalink,
|
|
256
|
+
"created_utc": created_utc,
|
|
257
|
+
"is_video": is_video,
|
|
258
|
+
"media_url": media_url,
|
|
259
|
+
})
|
|
260
|
+
|
|
261
|
+
# Save to Outputs/text_posts/
|
|
262
|
+
base_out = Path(output_dir) if output_dir else (_outputs_dir() / "text_posts" / f"r_{clean_sub}")
|
|
263
|
+
base_out.mkdir(parents=True, exist_ok=True)
|
|
264
|
+
save_path = base_out / f"{sort}_feed.json"
|
|
265
|
+
|
|
266
|
+
with open(save_path, "w", encoding="utf-8") as f:
|
|
267
|
+
json.dump({"subreddit": clean_sub, "sort": sort, "count": len(posts), "posts": posts}, f, indent=2)
|
|
268
|
+
|
|
269
|
+
return {
|
|
270
|
+
"status": "success",
|
|
271
|
+
"subreddit": clean_sub,
|
|
272
|
+
"sort": sort,
|
|
273
|
+
"count": len(posts),
|
|
274
|
+
"saved_path": str(save_path),
|
|
275
|
+
"posts": posts
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def get_reddit_post_and_comments(
|
|
280
|
+
post_url_or_id: str,
|
|
281
|
+
max_depth: int = 10,
|
|
282
|
+
output_dir: Optional[Union[Path, str]] = None
|
|
283
|
+
) -> Dict[str, Any]:
|
|
284
|
+
"""
|
|
285
|
+
Extracts complete post metadata along with the entire nested comment tree.
|
|
286
|
+
"""
|
|
287
|
+
parsed = parse_reddit_target(post_url_or_id)
|
|
288
|
+
post_id = parsed["id"]
|
|
289
|
+
|
|
290
|
+
url = parsed["url"] if parsed["url"].startswith("http") else f"https://www.reddit.com/comments/{post_id}"
|
|
291
|
+
data = _safe_json_get(url)
|
|
292
|
+
|
|
293
|
+
if not data or not isinstance(data, list) or len(data) < 2:
|
|
294
|
+
return {
|
|
295
|
+
"status": "error",
|
|
296
|
+
"post_id": post_id,
|
|
297
|
+
"error": f"Failed to retrieve discussion tree for {post_id}.",
|
|
298
|
+
"post": None,
|
|
299
|
+
"comments": []
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
# Element 0 is the Post listing
|
|
303
|
+
post_data = data[0].get("data", {}).get("children", [{}])[0].get("data", {})
|
|
304
|
+
post_info = {
|
|
305
|
+
"id": post_data.get("id", post_id),
|
|
306
|
+
"title": post_data.get("title", ""),
|
|
307
|
+
"author": post_data.get("author", "[deleted]"),
|
|
308
|
+
"subreddit": post_data.get("subreddit", ""),
|
|
309
|
+
"text": post_data.get("selftext", ""),
|
|
310
|
+
"score": post_data.get("score", 0),
|
|
311
|
+
"upvote_ratio": post_data.get("upvote_ratio", 0.0),
|
|
312
|
+
"num_comments": post_data.get("num_comments", 0),
|
|
313
|
+
"created_utc": post_data.get("created_utc", 0),
|
|
314
|
+
"permalink": f"https://reddit.com{post_data.get('permalink', '')}",
|
|
315
|
+
"media_url": post_data.get("url_overridden_by_dest") or post_data.get("url"),
|
|
316
|
+
"is_video": post_data.get("is_video", False)
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
# Element 1 is the Comments listing
|
|
320
|
+
comments_children = data[1].get("data", {}).get("children", [])
|
|
321
|
+
comments = []
|
|
322
|
+
for child in comments_children:
|
|
323
|
+
parsed_comment = _parse_comment_tree(child, depth=0, max_depth=max_depth)
|
|
324
|
+
if parsed_comment:
|
|
325
|
+
comments.append(parsed_comment)
|
|
326
|
+
|
|
327
|
+
# Save to Outputs/comments/
|
|
328
|
+
base_out = Path(output_dir) if output_dir else (_outputs_dir() / "comments" / post_id)
|
|
329
|
+
base_out.mkdir(parents=True, exist_ok=True)
|
|
330
|
+
save_path = base_out / "comment_tree.json"
|
|
331
|
+
|
|
332
|
+
result_bundle = {
|
|
333
|
+
"post": post_info,
|
|
334
|
+
"comments_count": len(comments),
|
|
335
|
+
"comments": comments
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
with open(save_path, "w", encoding="utf-8") as f:
|
|
339
|
+
json.dump(result_bundle, f, indent=2)
|
|
340
|
+
|
|
341
|
+
return {
|
|
342
|
+
"status": "success",
|
|
343
|
+
"post_id": post_id,
|
|
344
|
+
"saved_path": str(save_path),
|
|
345
|
+
"post": post_info,
|
|
346
|
+
"comments_count": len(comments),
|
|
347
|
+
"comments": comments
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def get_reddit_user_history(
|
|
352
|
+
username: str,
|
|
353
|
+
limit: int = 25,
|
|
354
|
+
output_dir: Optional[Union[Path, str]] = None
|
|
355
|
+
) -> Dict[str, Any]:
|
|
356
|
+
"""
|
|
357
|
+
Extracts user submissions and comments history.
|
|
358
|
+
"""
|
|
359
|
+
clean_user = username.replace("u/", "").replace("user/", "").strip("/")
|
|
360
|
+
url = f"https://www.reddit.com/user/{clean_user}.json"
|
|
361
|
+
params = {"limit": min(limit, 100)}
|
|
362
|
+
|
|
363
|
+
data = _safe_json_get(url, params=params)
|
|
364
|
+
if not data or not isinstance(data, dict):
|
|
365
|
+
return {
|
|
366
|
+
"status": "error",
|
|
367
|
+
"username": clean_user,
|
|
368
|
+
"error": f"Failed to retrieve user history for u/{clean_user}.",
|
|
369
|
+
"items": []
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
children = data.get("data", {}).get("children", [])
|
|
373
|
+
items = []
|
|
374
|
+
for c in children:
|
|
375
|
+
kind = c.get("kind")
|
|
376
|
+
d = c.get("data", {})
|
|
377
|
+
item_type = "post" if kind == "t3" else "comment" if kind == "t1" else kind
|
|
378
|
+
items.append({
|
|
379
|
+
"type": item_type,
|
|
380
|
+
"id": d.get("id"),
|
|
381
|
+
"subreddit": d.get("subreddit"),
|
|
382
|
+
"title": d.get("title") if item_type == "post" else d.get("link_title"),
|
|
383
|
+
"body_or_text": d.get("selftext") if item_type == "post" else d.get("body"),
|
|
384
|
+
"score": d.get("score", 0),
|
|
385
|
+
"created_utc": d.get("created_utc", 0),
|
|
386
|
+
"permalink": f"https://reddit.com{d.get('permalink', '')}"
|
|
387
|
+
})
|
|
388
|
+
|
|
389
|
+
base_out = Path(output_dir) if output_dir else (_outputs_dir() / "text_posts" / f"u_{clean_user}")
|
|
390
|
+
base_out.mkdir(parents=True, exist_ok=True)
|
|
391
|
+
save_path = base_out / "user_history.json"
|
|
392
|
+
|
|
393
|
+
with open(save_path, "w", encoding="utf-8") as f:
|
|
394
|
+
json.dump({"username": clean_user, "count": len(items), "items": items}, f, indent=2)
|
|
395
|
+
|
|
396
|
+
return {
|
|
397
|
+
"status": "success",
|
|
398
|
+
"username": clean_user,
|
|
399
|
+
"count": len(items),
|
|
400
|
+
"saved_path": str(save_path),
|
|
401
|
+
"items": items
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def search_reddit(
|
|
406
|
+
query: str,
|
|
407
|
+
subreddit: Optional[str] = None,
|
|
408
|
+
sort: str = "relevance",
|
|
409
|
+
time_filter: str = "all",
|
|
410
|
+
limit: int = 25,
|
|
411
|
+
output_dir: Optional[Union[Path, str]] = None
|
|
412
|
+
) -> Dict[str, Any]:
|
|
413
|
+
"""
|
|
414
|
+
Performs a keyword search across all of Reddit or restricted to a specific subreddit.
|
|
415
|
+
"""
|
|
416
|
+
if subreddit:
|
|
417
|
+
clean_sub = subreddit.replace("r/", "").strip("/")
|
|
418
|
+
url = f"https://www.reddit.com/r/{clean_sub}/search.json"
|
|
419
|
+
params: Dict[str, Any] = {"q": query, "restrict_sr": "1", "sort": sort, "t": time_filter, "limit": min(limit, 100)}
|
|
420
|
+
else:
|
|
421
|
+
url = "https://www.reddit.com/search.json"
|
|
422
|
+
params = {"q": query, "sort": sort, "t": time_filter, "limit": min(limit, 100)}
|
|
423
|
+
|
|
424
|
+
data = _safe_json_get(url, params=params)
|
|
425
|
+
if not data or not isinstance(data, dict):
|
|
426
|
+
return {
|
|
427
|
+
"status": "error",
|
|
428
|
+
"query": query,
|
|
429
|
+
"subreddit": subreddit,
|
|
430
|
+
"error": "Failed to execute Reddit search.",
|
|
431
|
+
"results": []
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
children = data.get("data", {}).get("children", [])
|
|
435
|
+
results = []
|
|
436
|
+
for c in children:
|
|
437
|
+
d = c.get("data", {})
|
|
438
|
+
results.append({
|
|
439
|
+
"id": d.get("id"),
|
|
440
|
+
"subreddit": d.get("subreddit"),
|
|
441
|
+
"title": d.get("title"),
|
|
442
|
+
"author": d.get("author"),
|
|
443
|
+
"text": d.get("selftext", ""),
|
|
444
|
+
"score": d.get("score", 0),
|
|
445
|
+
"comments_count": d.get("num_comments", 0),
|
|
446
|
+
"permalink": f"https://reddit.com{d.get('permalink', '')}",
|
|
447
|
+
"created_utc": d.get("created_utc", 0),
|
|
448
|
+
"media_url": d.get("url_overridden_by_dest") or d.get("url")
|
|
449
|
+
})
|
|
450
|
+
|
|
451
|
+
slug = re.sub(r"[^a-zA-Z0-9_-]", "_", query)[:30]
|
|
452
|
+
base_out = Path(output_dir) if output_dir else (_outputs_dir() / "text_posts" / "searches")
|
|
453
|
+
base_out.mkdir(parents=True, exist_ok=True)
|
|
454
|
+
save_path = base_out / f"search_{slug}.json"
|
|
455
|
+
|
|
456
|
+
with open(save_path, "w", encoding="utf-8") as f:
|
|
457
|
+
json.dump({"query": query, "subreddit": subreddit, "count": len(results), "results": results}, f, indent=2)
|
|
458
|
+
|
|
459
|
+
return {
|
|
460
|
+
"status": "success",
|
|
461
|
+
"query": query,
|
|
462
|
+
"subreddit": subreddit,
|
|
463
|
+
"count": len(results),
|
|
464
|
+
"saved_path": str(save_path),
|
|
465
|
+
"results": results
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def download_reddit_media(
|
|
470
|
+
post_url_or_id: str,
|
|
471
|
+
output_dir: Optional[Union[Path, str]] = None,
|
|
472
|
+
download_video: bool = True,
|
|
473
|
+
download_thumbnail: bool = True,
|
|
474
|
+
quality: str = "best"
|
|
475
|
+
) -> Dict[str, Any]:
|
|
476
|
+
"""
|
|
477
|
+
Downloads attached Reddit-hosted video (v.redd.it), preview images, or media using yt-dlp.
|
|
478
|
+
"""
|
|
479
|
+
parsed = parse_reddit_target(post_url_or_id)
|
|
480
|
+
post_id = parsed["id"]
|
|
481
|
+
url = parsed["url"] if parsed["url"].startswith("http") else f"https://www.reddit.com/comments/{post_id}"
|
|
482
|
+
|
|
483
|
+
if not HAS_YT_DLP:
|
|
484
|
+
return {
|
|
485
|
+
"status": "error",
|
|
486
|
+
"post_id": post_id,
|
|
487
|
+
"error": "yt-dlp is required for Reddit media downloads.",
|
|
488
|
+
"video_path": None,
|
|
489
|
+
"thumbnail_path": None
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
base_out = Path(output_dir) if output_dir else (_outputs_dir() / "videos" / post_id)
|
|
493
|
+
base_out.mkdir(parents=True, exist_ok=True)
|
|
494
|
+
thumb_out = _outputs_dir() / "thumbnails" / post_id
|
|
495
|
+
thumb_out.mkdir(parents=True, exist_ok=True)
|
|
496
|
+
|
|
497
|
+
result: Dict[str, Any] = {
|
|
498
|
+
"status": "success",
|
|
499
|
+
"post_id": post_id,
|
|
500
|
+
"video_path": None,
|
|
501
|
+
"thumbnail_path": None,
|
|
502
|
+
"title": None,
|
|
503
|
+
"error": None
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
try:
|
|
507
|
+
if download_thumbnail:
|
|
508
|
+
ydl_thumb_opts = {
|
|
509
|
+
"skip_download": True,
|
|
510
|
+
"writethumbnail": True,
|
|
511
|
+
"outtmpl": str(thumb_out / "thumbnail.%(ext)s"),
|
|
512
|
+
"quiet": True,
|
|
513
|
+
"no_warnings": True,
|
|
514
|
+
}
|
|
515
|
+
with yt_dlp.YoutubeDL(ydl_thumb_opts) as ydl:
|
|
516
|
+
info = ydl.extract_info(url, download=True)
|
|
517
|
+
result["title"] = info.get("title")
|
|
518
|
+
for ext in ["jpg", "jpeg", "png", "webp"]:
|
|
519
|
+
p = thumb_out / f"thumbnail.{ext}"
|
|
520
|
+
if p.exists():
|
|
521
|
+
result["thumbnail_path"] = str(p)
|
|
522
|
+
break
|
|
523
|
+
|
|
524
|
+
if download_video:
|
|
525
|
+
format_spec = "bestvideo+bestaudio/best" if quality == "best" else f"bestvideo[height<={quality.rstrip('p')}]+bestaudio/best[height<={quality.rstrip('p')}]"
|
|
526
|
+
ydl_video_opts = {
|
|
527
|
+
"format": format_spec,
|
|
528
|
+
"outtmpl": str(base_out / "video.%(ext)s"),
|
|
529
|
+
"quiet": True,
|
|
530
|
+
"no_warnings": True,
|
|
531
|
+
"merge_output_format": "mp4",
|
|
532
|
+
}
|
|
533
|
+
with yt_dlp.YoutubeDL(ydl_video_opts) as ydl:
|
|
534
|
+
info = ydl.extract_info(url, download=True)
|
|
535
|
+
result["title"] = info.get("title", result["title"])
|
|
536
|
+
for ext in ["mp4", "mkv", "webm"]:
|
|
537
|
+
p = base_out / f"video.{ext}"
|
|
538
|
+
if p.exists():
|
|
539
|
+
result["video_path"] = str(p)
|
|
540
|
+
break
|
|
541
|
+
|
|
542
|
+
except Exception as e:
|
|
543
|
+
result["status"] = "partial" if (result["video_path"] or result["thumbnail_path"]) else "error"
|
|
544
|
+
result["error"] = str(e)
|
|
545
|
+
|
|
546
|
+
return result
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "reddit-discussion-scraper",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Zero-cost Reddit discussion scraper for subreddit feeds, nested comment trees, user history, searches, and v.redd.it media downloads.",
|
|
5
|
+
"author": "SocialScrape",
|
|
6
|
+
"main": "cli.py",
|
|
7
|
+
"display_name": "Reddit Scraper",
|
|
8
|
+
"command": "/reddit",
|
|
9
|
+
"command_description": "subreddit feeds, nested comment trees & media",
|
|
10
|
+
"aliases": ["/reddit"],
|
|
11
|
+
"cli_aliases": ["reddit"],
|
|
12
|
+
"url_patterns": ["reddit.com", "redd.it", "r/", "u/"],
|
|
13
|
+
"tool_schema": {
|
|
14
|
+
"name": "reddit_scrape",
|
|
15
|
+
"description": "Scrapes Reddit subreddit feeds, deep nested comment trees, user submission/comment history, and downloads videos/thumbnails.",
|
|
16
|
+
"parameters": {
|
|
17
|
+
"type": "object",
|
|
18
|
+
"properties": {
|
|
19
|
+
"target": {"type": "string", "description": "Subreddit (e.g. 'r/sales'), post URL, user (e.g. 'u/username'), or search query."},
|
|
20
|
+
"input_file": {"type": "string", "description": "Path to .txt or .csv file for bulk Reddit targets."},
|
|
21
|
+
"sort": {"type": "string", "enum": ["hot", "new", "top", "rising"]},
|
|
22
|
+
"time_filter": {"type": "string", "enum": ["hour", "day", "week", "month", "year", "all"]},
|
|
23
|
+
"comments": {"type": "boolean", "description": "Extract nested comment tree."},
|
|
24
|
+
"user": {"type": "boolean", "description": "Extract user activity history."},
|
|
25
|
+
"search": {"type": "string", "description": "Search query."},
|
|
26
|
+
"download_video": {"type": "boolean"},
|
|
27
|
+
"download_thumbnail": {"type": "boolean"},
|
|
28
|
+
"limit": {"type": "integer"}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"flag_mapping": {
|
|
33
|
+
"positional": ["target"],
|
|
34
|
+
"flags": {
|
|
35
|
+
"input_file": "--input-file",
|
|
36
|
+
"sort": "--sort",
|
|
37
|
+
"time_filter": "--time",
|
|
38
|
+
"comments": "--comments",
|
|
39
|
+
"user": "--user",
|
|
40
|
+
"search": "--search",
|
|
41
|
+
"limit": "-l",
|
|
42
|
+
"download_video": "--download-video",
|
|
43
|
+
"download_thumbnail": "--download-thumb"
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Shared utilities for SocialScrape plugins.
|
|
3
|
+
"""
|
|
4
|
+
from .session_manager import SessionManager, RateLimiter
|
|
5
|
+
from .process_runner import run_plugin_subprocess
|
|
6
|
+
from .paths import get_plugin_outputs_dir, get_shared_state_dir, is_allowed_output_dir
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"SessionManager",
|
|
10
|
+
"RateLimiter",
|
|
11
|
+
"run_plugin_subprocess",
|
|
12
|
+
"get_plugin_outputs_dir",
|
|
13
|
+
"get_shared_state_dir",
|
|
14
|
+
"is_allowed_output_dir",
|
|
15
|
+
]
|