@auscera/socialscrape 0.0.0-stage → 2.0.1

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.
Files changed (63) hide show
  1. package/README.md +111 -2
  2. package/bin/socialscrape.mjs +115 -0
  3. package/engine/README.md +243 -0
  4. package/engine/SKILL.md +194 -0
  5. package/engine/agent.py +665 -0
  6. package/engine/batch_manager.py +622 -0
  7. package/engine/cli.py +23 -0
  8. package/engine/handlers.py +1109 -0
  9. package/engine/plugins/__init__.py +77 -0
  10. package/engine/plugins/instagram-scrape/README.md +164 -0
  11. package/engine/plugins/instagram-scrape/SKILL.md +53 -0
  12. package/engine/plugins/instagram-scrape/cli.py +176 -0
  13. package/engine/plugins/instagram-scrape/core.py +408 -0
  14. package/engine/plugins/instagram-scrape/plugin.json +42 -0
  15. package/engine/plugins/linkedin-scrape/README.md +143 -0
  16. package/engine/plugins/linkedin-scrape/SKILL.md +47 -0
  17. package/engine/plugins/linkedin-scrape/cli.py +126 -0
  18. package/engine/plugins/linkedin-scrape/core.py +188 -0
  19. package/engine/plugins/linkedin-scrape/plugin.json +36 -0
  20. package/engine/plugins/meta-ad-library-scraper/README.md +127 -0
  21. package/engine/plugins/meta-ad-library-scraper/SKILL.md +44 -0
  22. package/engine/plugins/meta-ad-library-scraper/cli.py +161 -0
  23. package/engine/plugins/meta-ad-library-scraper/core.py +348 -0
  24. package/engine/plugins/meta-ad-library-scraper/plugin.json +44 -0
  25. package/engine/plugins/pinterest-scraper/README.md +150 -0
  26. package/engine/plugins/pinterest-scraper/SKILL.md +45 -0
  27. package/engine/plugins/pinterest-scraper/cli.py +193 -0
  28. package/engine/plugins/pinterest-scraper/core.py +420 -0
  29. package/engine/plugins/pinterest-scraper/plugin.json +40 -0
  30. package/engine/plugins/reddit-discussion-scraper/README.md +162 -0
  31. package/engine/plugins/reddit-discussion-scraper/SKILL.md +52 -0
  32. package/engine/plugins/reddit-discussion-scraper/cli.py +218 -0
  33. package/engine/plugins/reddit-discussion-scraper/core.py +546 -0
  34. package/engine/plugins/reddit-discussion-scraper/plugin.json +46 -0
  35. package/engine/plugins/shared/__init__.py +15 -0
  36. package/engine/plugins/shared/paths.py +90 -0
  37. package/engine/plugins/shared/process_runner.py +169 -0
  38. package/engine/plugins/shared/session_manager.py +287 -0
  39. package/engine/plugins/threads-scraper/README.md +139 -0
  40. package/engine/plugins/threads-scraper/SKILL.md +43 -0
  41. package/engine/plugins/threads-scraper/cli.py +178 -0
  42. package/engine/plugins/threads-scraper/core.py +460 -0
  43. package/engine/plugins/threads-scraper/plugin.json +40 -0
  44. package/engine/plugins/tiktok-scrape/README.md +158 -0
  45. package/engine/plugins/tiktok-scrape/SKILL.md +51 -0
  46. package/engine/plugins/tiktok-scrape/cli.py +163 -0
  47. package/engine/plugins/tiktok-scrape/core.py +313 -0
  48. package/engine/plugins/tiktok-scrape/plugin.json +40 -0
  49. package/engine/plugins/twitter-scrape/README.md +158 -0
  50. package/engine/plugins/twitter-scrape/SKILL.md +50 -0
  51. package/engine/plugins/twitter-scrape/cli.py +153 -0
  52. package/engine/plugins/twitter-scrape/core.py +254 -0
  53. package/engine/plugins/twitter-scrape/plugin.json +40 -0
  54. package/engine/plugins/youtube-scrape/README.md +199 -0
  55. package/engine/plugins/youtube-scrape/SKILL.md +115 -0
  56. package/engine/plugins/youtube-scrape/cli.py +340 -0
  57. package/engine/plugins/youtube-scrape/core.py +829 -0
  58. package/engine/plugins/youtube-scrape/plugin.json +48 -0
  59. package/engine/requirements.txt +8 -0
  60. package/engine/socialscrape_cli.py +500 -0
  61. package/engine/storage.py +570 -0
  62. package/engine/ui.py +690 -0
  63. package/package.json +27 -3
@@ -0,0 +1,161 @@
1
+ """
2
+ Meta / Facebook Ad Library Scraper CLI (`cli.py`)
3
+ Interactive wizard and command-line presentation layer for meta-ad-library-scraper.
4
+ """
5
+
6
+ import os
7
+ import sys
8
+ import json
9
+ import argparse
10
+ from pathlib import Path
11
+ from typing import Dict, Any
12
+
13
+ sys.stdout.reconfigure(encoding="utf-8")
14
+ PLUGIN_DIR = Path(__file__).parent.resolve()
15
+ try:
16
+ from plugins.shared.paths import get_plugin_outputs_dir
17
+ except ImportError:
18
+ _shared_parent = str(PLUGIN_DIR.parent.resolve())
19
+ if _shared_parent not in sys.path:
20
+ sys.path.insert(0, _shared_parent)
21
+ from shared.paths import get_plugin_outputs_dir
22
+
23
+ DEFAULT_OUTPUTS_DIR = get_plugin_outputs_dir(PLUGIN_DIR)
24
+
25
+ try:
26
+ from core import (
27
+ extract_meta_ad_target,
28
+ search_meta_ads,
29
+ get_company_active_ads,
30
+ download_meta_ad_media,
31
+ )
32
+ except ImportError:
33
+ sys.path.insert(0, str(PLUGIN_DIR))
34
+ from core import (
35
+ extract_meta_ad_target,
36
+ search_meta_ads,
37
+ get_company_active_ads,
38
+ download_meta_ad_media,
39
+ )
40
+
41
+
42
+ def run_interactive_wizard():
43
+ print("=" * 65)
44
+ print(" 💎 Meta / Facebook Ad Library Intelligence Wizard")
45
+ print("=" * 65)
46
+ print("\nSelect Option:")
47
+ print(" [1] Search Active Ads by Keyword / Niche")
48
+ print(" [2] Search Competitor Active Ads by Facebook Page ID")
49
+ print(" [3] Download Video Ad or Creative Image (MP4/JPG)")
50
+ print(" [4] Full Extraction Suite (--all)")
51
+
52
+ choice = input("\nEnter choice [1-4] (default: 1): ").strip() or "1"
53
+
54
+ if choice == "1":
55
+ keyword = input("\nEnter Brand name or Search Keyword (e.g. 'cold calling software'): ").strip()
56
+ if not keyword:
57
+ print("[!] No keyword specified. Exiting.")
58
+ return
59
+ country = input("Target Country Code [US/GB/CA/ALL] (default: ALL): ").strip().upper() or "ALL"
60
+ media_type = input("Media Type [all/video/image/meme] (default: all): ").strip().lower() or "all"
61
+ limit_str = input("Limit ads count (default: 25): ").strip() or "25"
62
+ limit = int(limit_str) if limit_str.isdigit() else 25
63
+
64
+ print(f"\n[+] Searching Meta Ad Library for '{keyword}' ({country})...")
65
+ res = search_meta_ads(keyword, country=country, media_type=media_type, limit=limit)
66
+ if res.get("status") == "success":
67
+ print(f"\n✅ Extracted {res['count']} active ads for '{keyword}'")
68
+ print(f"💾 Saved to: {res.get('saved_path')}")
69
+ for idx, ad in enumerate(res["ads"][:5], 1):
70
+ body_prev = ad.get("body_text", "") or "No body text"
71
+ body_prev = body_prev[:80] + "..." if len(body_prev) > 80 else body_prev
72
+ print(f" {idx}. [ID: {ad.get('ad_archive_id')}] {ad.get('page_name')}: {body_prev}")
73
+ else:
74
+ print(f"[!] Error: {res.get('error')}")
75
+
76
+ elif choice == "2":
77
+ page_id = input("\nEnter Facebook Page ID (e.g. '1234567890'): ").strip()
78
+ if not page_id:
79
+ print("[!] No Page ID specified. Exiting.")
80
+ return
81
+ print(f"\n[+] Fetching active ads for Page {page_id}...")
82
+ res = get_company_active_ads(page_id)
83
+ if res.get("status") == "success":
84
+ print(f"\n✅ Found {res['count']} active ads for Page ID {page_id}")
85
+ print(f"💾 Saved to: {res.get('saved_path')}")
86
+ else:
87
+ print(f"[!] Error: {res.get('error')}")
88
+
89
+ elif choice == "3":
90
+ ad_id = input("\nEnter Meta Ad Archive ID or URL: ").strip()
91
+ print(f"\n[+] Downloading Creative Media for Ad {ad_id}...")
92
+ res = download_meta_ad_media(ad_id)
93
+ if res.get("status") == "success":
94
+ print(f"\n✅ Download complete!")
95
+ if res.get("video_path"):
96
+ print(f" 🎬 Video Ad saved: {res['video_path']}")
97
+ if res.get("thumbnail_path"):
98
+ print(f" 🖼️ Image Creative: {res['thumbnail_path']}")
99
+ else:
100
+ print(f"[!] Notice: {res.get('error')}")
101
+
102
+ elif choice == "4":
103
+ target = input("\nEnter Keyword or Page ID: ").strip()
104
+ print(f"\n[+] Running Full Meta Ad Suite on {target}...")
105
+ parsed = extract_meta_ad_target(target)
106
+ if parsed["type"] == "page_id":
107
+ res = get_company_active_ads(parsed["id"])
108
+ else:
109
+ res = search_meta_ads(target)
110
+ print(json.dumps(res, indent=2, default=str))
111
+
112
+
113
+ def main():
114
+ parser = argparse.ArgumentParser(description="Meta / Facebook Ad Library Intelligence CLI")
115
+ parser.add_argument("target", nargs="?", help="Keyword, Page ID, or Ad Archive URL")
116
+ parser.add_argument("-i", "--interactive", action="store_true", help="Launch interactive wizard")
117
+ parser.add_argument("--page-id", type=str, help="Search ads by Page ID")
118
+ parser.add_argument("--country", default="ALL", help="Country code filter (e.g. US, GB, ALL)")
119
+ parser.add_argument("--media-type", default="all", choices=["all", "video", "image", "meme"], help="Filter by media type")
120
+ parser.add_argument("--status", default="ACTIVE", choices=["ACTIVE", "INACTIVE", "ALL"], help="Ad active status")
121
+ parser.add_argument("-l", "--limit", type=int, default=25, help="Number of ads to extract")
122
+ parser.add_argument("--download-video", action="store_true", help="Download video ad MP4")
123
+ parser.add_argument("--download-thumb", action="store_true", help="Download creative image")
124
+ parser.add_argument("--stdout", action="store_true", help="Output raw JSON to stdout")
125
+ parser.add_argument("--output-dir", "-o", type=str, default=str(DEFAULT_OUTPUTS_DIR), help="Output base directory.")
126
+
127
+ args = parser.parse_args()
128
+ if args.output_dir:
129
+ os.environ["SOCIALSCRAPE_OUTPUT_DIR"] = str(Path(args.output_dir).expanduser().resolve())
130
+
131
+ if args.interactive or (not args.target and not args.page_id):
132
+ run_interactive_wizard()
133
+ return
134
+
135
+ result = {}
136
+
137
+ if args.page_id:
138
+ result = get_company_active_ads(args.page_id, country=args.country, limit=args.limit)
139
+ elif args.target:
140
+ parsed = extract_meta_ad_target(args.target)
141
+ if parsed["type"] == "page_id":
142
+ result = get_company_active_ads(parsed["id"], country=args.country, limit=args.limit)
143
+ elif parsed["type"] == "ad_id":
144
+ result = download_meta_ad_media(parsed["id"], download_video=args.download_video, download_thumbnail=args.download_thumb)
145
+ else:
146
+ result = search_meta_ads(args.target, country=args.country, media_type=args.media_type, status=args.status, limit=args.limit)
147
+
148
+ if args.stdout:
149
+ print(json.dumps(result, indent=2, default=str))
150
+ else:
151
+ status = result.get("status")
152
+ if status == "success":
153
+ print(f"✅ Extraction completed successfully!")
154
+ if "saved_path" in result:
155
+ print(f"💾 File: {result['saved_path']}")
156
+ else:
157
+ print(f"[!] Notice: {result.get('error', 'Operation finished with warnings.')}")
158
+
159
+
160
+ if __name__ == "__main__":
161
+ main()
@@ -0,0 +1,348 @@
1
+ """
2
+ Meta / Facebook Ad Library Scraper Pure SDK (`core.py`)
3
+ Pure zero-side-effect Python SDK for Meta Ad Library data extraction, competitor swipe files, and video ad downloading.
4
+ Utilizes the public Meta Ad Library async search endpoint with SessionManager cookie injection and rate limiting.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import json
10
+ import re
11
+ import time
12
+ import random
13
+ import urllib.parse
14
+ from pathlib import Path
15
+ from typing import Dict, List, Any, Optional, Union
16
+
17
+ try:
18
+ import requests
19
+ HAS_REQUESTS = True
20
+ except ImportError:
21
+ HAS_REQUESTS = False
22
+
23
+ try:
24
+ import yt_dlp
25
+ HAS_YT_DLP = True
26
+ except ImportError:
27
+ HAS_YT_DLP = False
28
+
29
+ # Import shared SessionManager & Path Helpers
30
+ try:
31
+ from plugins.shared.session_manager import SessionManager, RateLimiter
32
+ from plugins.shared.paths import get_plugin_outputs_dir
33
+ HAS_SESSION_MANAGER = True
34
+ except ImportError:
35
+ _shared_parent = str(Path(__file__).parent.parent.resolve())
36
+ if _shared_parent not in sys.path:
37
+ sys.path.insert(0, _shared_parent)
38
+ from shared.paths import get_plugin_outputs_dir
39
+ try:
40
+ from shared.session_manager import SessionManager, RateLimiter
41
+ HAS_SESSION_MANAGER = True
42
+ except ImportError:
43
+ HAS_SESSION_MANAGER = False
44
+
45
+ PLUGIN_DIR = Path(__file__).parent.resolve()
46
+ DEFAULT_OUTPUTS_DIR = get_plugin_outputs_dir(PLUGIN_DIR)
47
+
48
+
49
+ def _outputs_dir() -> Path:
50
+ return get_plugin_outputs_dir(PLUGIN_DIR)
51
+
52
+ USER_AGENTS = [
53
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
54
+ "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",
55
+ ]
56
+
57
+
58
+ def get_random_headers(fb_cookies: Optional[Dict[str, str]] = None) -> Dict[str, str]:
59
+ """Generates stealth headers for Meta Ad Library requests."""
60
+ headers = {
61
+ "User-Agent": random.choice(USER_AGENTS),
62
+ "Accept": "*/*",
63
+ "Accept-Language": "en-US,en;q=0.9",
64
+ "Origin": "https://www.facebook.com",
65
+ "Referer": "https://www.facebook.com/ads/library/",
66
+ "Sec-Fetch-Site": "same-origin",
67
+ "Sec-Fetch-Mode": "cors",
68
+ "Sec-Fetch-Dest": "empty",
69
+ }
70
+ if fb_cookies:
71
+ cookie_str = "; ".join([f"{k}={v}" for k, v in fb_cookies.items()])
72
+ headers["Cookie"] = cookie_str
73
+ return headers
74
+
75
+
76
+ def extract_meta_ad_target(target: str) -> Dict[str, str]:
77
+ """
78
+ Parses a raw Meta Ad target input.
79
+ Supported:
80
+ - Ad Archive URL: https://www.facebook.com/ads/library/?id=1234567890
81
+ - Ad Archive ID: 1234567890
82
+ - Page ID: page_123456
83
+ - Keyword: "cold calling", "AI automations"
84
+ """
85
+ t = target.strip()
86
+ if "id=" in t:
87
+ match = re.search(r"[?&]id=(\d+)", t)
88
+ ad_id = match.group(1) if match else t
89
+ return {"type": "ad_id", "id": ad_id, "url": t}
90
+ elif t.isdigit() and len(t) >= 8:
91
+ return {"type": "ad_id", "id": t, "url": f"https://www.facebook.com/ads/library/?id={t}"}
92
+ elif t.lower().startswith("page_") or t.lower().startswith("page:"):
93
+ page_id = re.sub(r"^page[_:]", "", t, flags=re.IGNORECASE)
94
+ return {"type": "page_id", "id": page_id, "url": t}
95
+
96
+ return {"type": "keyword", "id": t, "url": t}
97
+
98
+
99
+ def _get_fb_session_cookies() -> Optional[Dict[str, str]]:
100
+ """Retrieves stored Facebook burner session cookies if present."""
101
+ if not HAS_SESSION_MANAGER:
102
+ return None
103
+ try:
104
+ mgr = SessionManager()
105
+ sess = mgr.get_session("facebook") or mgr.get_session("meta")
106
+ if sess and "cookies" in sess:
107
+ return sess["cookies"]
108
+ except Exception:
109
+ pass
110
+ return None
111
+
112
+
113
+ def search_meta_ads(
114
+ query_or_page_id: str,
115
+ country: str = "ALL",
116
+ media_type: str = "all",
117
+ status: str = "ACTIVE",
118
+ is_page_id: bool = False,
119
+ limit: int = 25,
120
+ output_dir: Optional[Union[Path, str]] = None
121
+ ) -> Dict[str, Any]:
122
+ """
123
+ Searches active or inactive Meta Ads by keyword or Page ID via the async search endpoint.
124
+ Media types: 'all', 'video', 'image', 'meme'.
125
+ Status: 'ACTIVE', 'INACTIVE', 'ALL'.
126
+ """
127
+ if not HAS_REQUESTS:
128
+ return {"status": "error", "error": "requests library is required."}
129
+
130
+ # Enforce RateLimiter pacing
131
+ if HAS_SESSION_MANAGER:
132
+ try:
133
+ limiter = RateLimiter()
134
+ limiter.check_and_pace("meta_ads")
135
+ except Exception:
136
+ pass
137
+
138
+ fb_cookies = _get_fb_session_cookies()
139
+ headers = get_random_headers(fb_cookies)
140
+
141
+ url = "https://www.facebook.com/ads/library/async/search_ads/"
142
+ params: Dict[str, Any] = {
143
+ "count": min(limit, 50),
144
+ "active_status": status.lower(),
145
+ "ad_type": "all",
146
+ "countries[0]": country,
147
+ "media_type": media_type.lower(),
148
+ "sort_data[direction]": "desc",
149
+ "sort_data[mode]": "relevancy_monthly_grouped",
150
+ }
151
+
152
+ if is_page_id:
153
+ params["view_all_page_id"] = query_or_page_id
154
+ else:
155
+ params["q"] = query_or_page_id
156
+
157
+ try:
158
+ resp = requests.get(url, headers=headers, params=params, timeout=15)
159
+
160
+ # Facebook async responses prefix with for (;;);
161
+ raw_text = resp.text
162
+ if raw_text.startswith("for (;;);"):
163
+ raw_text = raw_text[9:]
164
+
165
+ ads: List[Dict[str, Any]] = []
166
+
167
+ try:
168
+ payload = json.loads(raw_text)
169
+ payload_data = payload.get("payload", {})
170
+ results = payload_data.get("results", [])
171
+
172
+ for item in results:
173
+ # Meta returns nested list of snapshot objects
174
+ for ad_obj in item if isinstance(item, list) else [item]:
175
+ snapshot = ad_obj.get("snapshot", {})
176
+ ad_id = ad_obj.get("adArchiveID") or snapshot.get("ad_creative_id")
177
+ body_markup = snapshot.get("body", {}).get("markup", {}).get("__html", "")
178
+ clean_body = re.sub(r"<[^>]+>", "", body_markup).strip()
179
+
180
+ # Extract creative cards
181
+ cards = snapshot.get("cards", [])
182
+ card_imgs = []
183
+ card_videos = []
184
+ for card in cards:
185
+ if card.get("resized_image_url"):
186
+ card_imgs.append(card["resized_image_url"])
187
+ if card.get("video_hd_url") or card.get("video_sd_url"):
188
+ card_videos.append(card.get("video_hd_url") or card["video_sd_url"])
189
+
190
+ videos_raw = snapshot.get("videos", [])
191
+ for v in videos_raw:
192
+ v_url = v.get("video_hd_url") or v.get("video_sd_url")
193
+ if v_url and v_url not in card_videos:
194
+ card_videos.append(v_url)
195
+
196
+ images_raw = snapshot.get("images", [])
197
+ for img in images_raw:
198
+ img_url = img.get("resized_image_url") or img.get("original_image_url")
199
+ if img_url and img_url not in card_imgs:
200
+ card_imgs.append(img_url)
201
+
202
+ ads.append({
203
+ "ad_archive_id": ad_id,
204
+ "page_id": snapshot.get("page_id"),
205
+ "page_name": snapshot.get("page_name"),
206
+ "body_text": clean_body,
207
+ "cta_text": snapshot.get("cta_text"),
208
+ "link_url": snapshot.get("link_url"),
209
+ "publisher_platform": snapshot.get("publisher_platform", []),
210
+ "start_date": snapshot.get("start_date"),
211
+ "end_date": snapshot.get("end_date"),
212
+ "image_urls": card_imgs,
213
+ "video_urls": card_videos,
214
+ })
215
+
216
+ except Exception as parse_err:
217
+ # Fallback regex parsing if JSON structure varies
218
+ ad_ids = re.findall(r'"adArchiveID":"?(\d+)"?', raw_text)
219
+ page_names = re.findall(r'"page_name":"([^"]+)"', raw_text)
220
+ body_matches = re.findall(r'"markup":\{"__html":"(.*?)"\}', raw_text)
221
+ for idx, aid in enumerate(set(ad_ids[:limit])):
222
+ pname = page_names[idx] if idx < len(page_names) else "Unknown Advertiser"
223
+ btext = re.sub(r"<[^>]+>", "", body_matches[idx]).strip() if idx < len(body_matches) else None
224
+ ads.append({
225
+ "ad_archive_id": aid,
226
+ "page_name": pname,
227
+ "body_text": btext,
228
+ "video_urls": [],
229
+ "image_urls": []
230
+ })
231
+
232
+ slug = re.sub(r"[^a-zA-Z0-9_-]", "_", query_or_page_id)[:30]
233
+ base_out = Path(output_dir) if output_dir else (_outputs_dir() / "text_posts" / f"meta_{slug}")
234
+ base_out.mkdir(parents=True, exist_ok=True)
235
+ save_path = base_out / "ads.json"
236
+
237
+ with open(save_path, "w", encoding="utf-8") as f:
238
+ json.dump({
239
+ "target": query_or_page_id,
240
+ "is_page_id": is_page_id,
241
+ "count": len(ads),
242
+ "ads": ads
243
+ }, f, indent=2)
244
+
245
+ return {
246
+ "status": "success",
247
+ "target": query_or_page_id,
248
+ "count": len(ads),
249
+ "saved_path": str(save_path),
250
+ "ads": ads
251
+ }
252
+
253
+ except Exception as e:
254
+ return {"status": "error", "target": query_or_page_id, "error": str(e)}
255
+
256
+
257
+ def get_company_active_ads(
258
+ page_id: str,
259
+ country: str = "ALL",
260
+ limit: int = 25,
261
+ output_dir: Optional[Union[Path, str]] = None
262
+ ) -> Dict[str, Any]:
263
+ """
264
+ Fetches all active competitor ads run by a specific Facebook Page ID.
265
+ """
266
+ clean_page_id = page_id.replace("page_", "").replace("page:", "").strip()
267
+ return search_meta_ads(
268
+ query_or_page_id=clean_page_id,
269
+ country=country,
270
+ is_page_id=True,
271
+ limit=limit,
272
+ output_dir=output_dir
273
+ )
274
+
275
+
276
+ def download_meta_ad_media(
277
+ ad_id_or_url: str,
278
+ video_url: Optional[str] = None,
279
+ image_url: Optional[str] = None,
280
+ output_dir: Optional[Union[Path, str]] = None,
281
+ download_video: bool = True,
282
+ download_thumbnail: bool = True
283
+ ) -> Dict[str, Any]:
284
+ """
285
+ Downloads raw CDN video ads (MP4) and creative images into standardized Outputs/.
286
+ """
287
+ parsed = extract_meta_ad_target(ad_id_or_url)
288
+ ad_id = parsed["id"]
289
+
290
+ base_out = Path(output_dir) if output_dir else (_outputs_dir() / "videos" / f"ad_{ad_id}")
291
+ base_out.mkdir(parents=True, exist_ok=True)
292
+ thumb_out = _outputs_dir() / "thumbnails" / f"ad_{ad_id}"
293
+ thumb_out.mkdir(parents=True, exist_ok=True)
294
+
295
+ result: Dict[str, Any] = {
296
+ "status": "success",
297
+ "ad_id": ad_id,
298
+ "video_path": None,
299
+ "thumbnail_path": None,
300
+ "error": None
301
+ }
302
+
303
+ # Direct video download if direct CDN URL provided
304
+ if download_video and video_url and HAS_REQUESTS:
305
+ try:
306
+ r = requests.get(video_url, headers=get_random_headers(), timeout=25)
307
+ if r.status_code == 200:
308
+ save_vid = base_out / "video_ad.mp4"
309
+ with open(save_vid, "wb") as f:
310
+ f.write(r.content)
311
+ result["video_path"] = str(save_vid)
312
+ except Exception as e:
313
+ result["error"] = str(e)
314
+
315
+ # Direct thumbnail download if provided
316
+ if download_thumbnail and image_url and HAS_REQUESTS:
317
+ try:
318
+ r = requests.get(image_url, headers=get_random_headers(), timeout=15)
319
+ if r.status_code == 200:
320
+ save_thumb = thumb_out / "ad_creative.jpg"
321
+ with open(save_thumb, "wb") as f:
322
+ f.write(r.content)
323
+ result["thumbnail_path"] = str(save_thumb)
324
+ except Exception as e:
325
+ result["error"] = str(e)
326
+
327
+ # Fallback to yt-dlp if URL is full Facebook video or ad URL
328
+ if download_video and not result["video_path"] and HAS_YT_DLP:
329
+ try:
330
+ target_url = parsed["url"] if parsed["url"].startswith("http") else f"https://www.facebook.com/ads/library/?id={ad_id}"
331
+ ydl_opts = {
332
+ "outtmpl": str(base_out / "video_ad.%(ext)s"),
333
+ "quiet": True,
334
+ "no_warnings": True,
335
+ "merge_output_format": "mp4",
336
+ }
337
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
338
+ ydl.extract_info(target_url, download=True)
339
+ for ext in ["mp4", "mkv", "webm"]:
340
+ p = base_out / f"video_ad.{ext}"
341
+ if p.exists():
342
+ result["video_path"] = str(p)
343
+ break
344
+ except Exception as ydl_err:
345
+ if not result.get("error"):
346
+ result["error"] = f"yt-dlp notice: {ydl_err}"
347
+
348
+ return result
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "meta-ad-library-scraper",
3
+ "version": "1.0.0",
4
+ "description": "Zero-cost Meta / Facebook Ad Library scraper for competitor active ads, ad copy text, advertiser details, and creative video/image downloads.",
5
+ "author": "SocialScrape",
6
+ "main": "cli.py",
7
+ "display_name": "Meta Ad Library Scraper",
8
+ "command": "/meta",
9
+ "command_description": "Meta / Facebook Ad Library competitor search",
10
+ "aliases": ["/meta"],
11
+ "cli_aliases": ["meta"],
12
+ "url_patterns": ["facebook.com/ads"],
13
+ "tool_schema": {
14
+ "name": "meta_ads_scrape",
15
+ "description": "Scrapes Meta / Facebook Ad Library competitor active ads, primary copy text, advertiser details, and video ad MP4 downloads.",
16
+ "parameters": {
17
+ "type": "object",
18
+ "properties": {
19
+ "target": {"type": "string", "description": "Brand search keyword, Page ID, or Ad Archive URL."},
20
+ "input_file": {"type": "string", "description": "Path to .txt or .csv file for bulk Meta Ad Library scraping."},
21
+ "page_id": {"type": "string", "description": "Facebook Page ID."},
22
+ "country": {"type": "string", "description": "Country code (e.g. US, GB, ALL)."},
23
+ "media_type": {"type": "string", "enum": ["all", "video", "image", "meme"]},
24
+ "status": {"type": "string", "enum": ["ACTIVE", "INACTIVE", "ALL"]},
25
+ "download_video": {"type": "boolean"},
26
+ "download_thumbnail": {"type": "boolean"},
27
+ "limit": {"type": "integer"}
28
+ }
29
+ }
30
+ },
31
+ "flag_mapping": {
32
+ "positional": ["target"],
33
+ "flags": {
34
+ "input_file": "--input-file",
35
+ "page_id": "--page-id",
36
+ "country": "--country",
37
+ "media_type": "--media-type",
38
+ "status": "--status",
39
+ "limit": "-l",
40
+ "download_video": "--download-video",
41
+ "download_thumbnail": "--download-thumb"
42
+ }
43
+ }
44
+ }