@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.
- package/README.md +111 -2
- package/bin/socialscrape.mjs +115 -0
- package/engine/README.md +243 -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,43 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: threads-scraper
|
|
3
|
+
description: "Self-contained plugin and skill for scraping Meta Threads user profiles, creator thread feeds, single thread discussions, and downloading attached media."
|
|
4
|
+
triggers:
|
|
5
|
+
- threads.net
|
|
6
|
+
- threads.net/@
|
|
7
|
+
- threads post
|
|
8
|
+
- threads profile
|
|
9
|
+
- threads feed
|
|
10
|
+
- download threads video
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
# Threads Scraper & Media Downloader Skill
|
|
14
|
+
|
|
15
|
+
## Overview
|
|
16
|
+
This plugin executes zero-cost extraction of Meta Threads profiles, posts, discussions, and media via dynamic LSD token extraction and public web endpoint parsing.
|
|
17
|
+
|
|
18
|
+
### Capabilities:
|
|
19
|
+
- **User Profiles**: Bio, follower counts, verified badges, full name, and avatar images.
|
|
20
|
+
- **Creator Feeds**: Scrape recent threads with like counts, text, and timestamps.
|
|
21
|
+
- **Thread Discussions**: Scrape post captions, replies, and author handles.
|
|
22
|
+
- **Media Downloader**: Extracts MP4 videos and images into `Outputs/videos/` and `Outputs/thumbnails/`.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## ⚡ CLI Usage Examples
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
# 1. Interactive Wizard
|
|
30
|
+
python plugins/threads-scraper/cli.py -i
|
|
31
|
+
|
|
32
|
+
# 2. Scrape User Profile
|
|
33
|
+
python plugins/threads-scraper/cli.py @zuck --profile
|
|
34
|
+
|
|
35
|
+
# 3. Scrape Creator Threads Feed
|
|
36
|
+
python plugins/threads-scraper/cli.py @zuck --feed --limit 20
|
|
37
|
+
|
|
38
|
+
# 4. Scrape Single Thread Discussion
|
|
39
|
+
python plugins/threads-scraper/cli.py "https://www.threads.net/@zuck/post/C8abc123"
|
|
40
|
+
|
|
41
|
+
# 5. Download Video / Media from Thread
|
|
42
|
+
python plugins/threads-scraper/cli.py "https://www.threads.net/@zuck/post/C8abc123" --download-video
|
|
43
|
+
```
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Threads Scraper CLI (`cli.py`)
|
|
3
|
+
Interactive wizard and command-line presentation layer for threads-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_threads_target,
|
|
28
|
+
get_threads_user_profile,
|
|
29
|
+
get_threads_user_posts,
|
|
30
|
+
get_thread_post_and_replies,
|
|
31
|
+
download_threads_media,
|
|
32
|
+
)
|
|
33
|
+
except ImportError:
|
|
34
|
+
sys.path.insert(0, str(PLUGIN_DIR))
|
|
35
|
+
from core import (
|
|
36
|
+
extract_threads_target,
|
|
37
|
+
get_threads_user_profile,
|
|
38
|
+
get_threads_user_posts,
|
|
39
|
+
get_thread_post_and_replies,
|
|
40
|
+
download_threads_media,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def run_interactive_wizard():
|
|
45
|
+
print("=" * 65)
|
|
46
|
+
print(" 🧵 Threads Universal Scraper & Downloader Wizard")
|
|
47
|
+
print("=" * 65)
|
|
48
|
+
print("\nSelect Option:")
|
|
49
|
+
print(" [1] Scrape User Profile & Bio (@handle)")
|
|
50
|
+
print(" [2] Scrape Creator Threads Feed")
|
|
51
|
+
print(" [3] Scrape Single Thread Discussion & Replies")
|
|
52
|
+
print(" [4] Download Video / Media from Thread (MP4)")
|
|
53
|
+
print(" [5] Full Extraction Suite (--all)")
|
|
54
|
+
|
|
55
|
+
choice = input("\nEnter choice [1-5] (default: 1): ").strip() or "1"
|
|
56
|
+
target = input("\nEnter Threads Post URL or @username: ").strip()
|
|
57
|
+
if not target:
|
|
58
|
+
print("[!] No target specified. Exiting.")
|
|
59
|
+
return
|
|
60
|
+
|
|
61
|
+
parsed = extract_threads_target(target)
|
|
62
|
+
|
|
63
|
+
if choice == "1":
|
|
64
|
+
print(f"\n[+] Fetching Profile for @{parsed['id']}...")
|
|
65
|
+
res = get_threads_user_profile(parsed["id"])
|
|
66
|
+
if res.get("status") == "success":
|
|
67
|
+
prof = res.get("profile", {})
|
|
68
|
+
print(f"\n✅ Profile Extracted:")
|
|
69
|
+
print(f" 👤 Name: {prof.get('full_name')} (@{prof.get('username')})")
|
|
70
|
+
print(f" 📝 Bio: {prof.get('bio')}")
|
|
71
|
+
print(f" ✔️ Verified: {'Yes' if prof.get('is_verified') else 'No'}")
|
|
72
|
+
print(f" 💾 Saved to: {res.get('saved_path')}")
|
|
73
|
+
else:
|
|
74
|
+
print(f"[!] Error: {res.get('error')}")
|
|
75
|
+
|
|
76
|
+
elif choice == "2":
|
|
77
|
+
limit_str = input("Limit posts count (default: 15): ").strip() or "15"
|
|
78
|
+
limit = int(limit_str) if limit_str.isdigit() else 15
|
|
79
|
+
print(f"\n[+] Fetching latest threads for @{parsed['id']}...")
|
|
80
|
+
res = get_threads_user_posts(parsed["id"], limit=limit)
|
|
81
|
+
if res.get("status") == "success":
|
|
82
|
+
print(f"\n✅ Extracted {res['count']} threads for @{parsed['id']}")
|
|
83
|
+
print(f"💾 Saved to: {res.get('saved_path')}")
|
|
84
|
+
for idx, p in enumerate(res["posts"][:5], 1):
|
|
85
|
+
text_preview = p.get("text", "")[:70] + "..." if len(p.get("text", "")) > 70 else p.get("text", "")
|
|
86
|
+
print(f" {idx}. [❤️ {p.get('likes', 0):,}] {text_preview}")
|
|
87
|
+
else:
|
|
88
|
+
print(f"[!] Error: {res.get('error')}")
|
|
89
|
+
|
|
90
|
+
elif choice == "3":
|
|
91
|
+
print(f"\n[+] Extracting Thread Discussion: {target}...")
|
|
92
|
+
res = get_thread_post_and_replies(target)
|
|
93
|
+
if res.get("status") == "success":
|
|
94
|
+
d = res.get("discussion", {})
|
|
95
|
+
print(f"\n✅ Thread Extracted:")
|
|
96
|
+
print(f" 👤 Author: @{d.get('author')}")
|
|
97
|
+
print(f" 📝 Content: {d.get('text')}")
|
|
98
|
+
print(f" 💾 Saved: {res.get('saved_path')}")
|
|
99
|
+
else:
|
|
100
|
+
print(f"[!] Error: {res.get('error')}")
|
|
101
|
+
|
|
102
|
+
elif choice == "4":
|
|
103
|
+
print(f"\n[+] Downloading Media for Thread {target}...")
|
|
104
|
+
res = download_threads_media(target)
|
|
105
|
+
if res.get("status") == "success":
|
|
106
|
+
print(f"\n✅ Download complete!")
|
|
107
|
+
if res.get("video_path"):
|
|
108
|
+
print(f" 🎬 Video saved: {res['video_path']}")
|
|
109
|
+
if res.get("thumbnail_path"):
|
|
110
|
+
print(f" 🖼️ Preview saved: {res['thumbnail_path']}")
|
|
111
|
+
else:
|
|
112
|
+
print(f"[!] Notice: {res.get('error')}")
|
|
113
|
+
|
|
114
|
+
elif choice == "5":
|
|
115
|
+
print(f"\n[+] Running Full Extraction Suite on {target}...")
|
|
116
|
+
if parsed["type"] == "user":
|
|
117
|
+
p = get_threads_user_profile(parsed["id"])
|
|
118
|
+
f = get_threads_user_posts(parsed["id"])
|
|
119
|
+
print(json.dumps({"profile": p, "feed": f}, indent=2, default=str))
|
|
120
|
+
else:
|
|
121
|
+
t = get_thread_post_and_replies(target)
|
|
122
|
+
d = download_threads_media(target)
|
|
123
|
+
print(json.dumps({"thread": t, "media": d}, indent=2, default=str))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def main():
|
|
127
|
+
parser = argparse.ArgumentParser(description="Threads Scraper & Media Downloader CLI")
|
|
128
|
+
parser.add_argument("target", nargs="?", help="Threads Post URL or @username")
|
|
129
|
+
parser.add_argument("-i", "--interactive", action="store_true", help="Launch interactive wizard")
|
|
130
|
+
parser.add_argument("--profile", action="store_true", help="Extract user profile info")
|
|
131
|
+
parser.add_argument("--feed", action="store_true", help="Scrape user threads feed")
|
|
132
|
+
parser.add_argument("--post", action="store_true", help="Scrape single post discussion")
|
|
133
|
+
parser.add_argument("-l", "--limit", type=int, default=15, help="Number of items to extract")
|
|
134
|
+
parser.add_argument("--download-video", action="store_true", help="Download MP4 video")
|
|
135
|
+
parser.add_argument("--download-thumb", action="store_true", help="Download image attachment")
|
|
136
|
+
parser.add_argument("-q", "--quality", default="best", choices=["best", "1080p", "720p", "480p"], help="Media quality")
|
|
137
|
+
parser.add_argument("--stdout", action="store_true", help="Output raw JSON to stdout")
|
|
138
|
+
parser.add_argument("--output-dir", "-o", type=str, default=str(DEFAULT_OUTPUTS_DIR), help="Output base directory.")
|
|
139
|
+
|
|
140
|
+
args = parser.parse_args()
|
|
141
|
+
if args.output_dir:
|
|
142
|
+
os.environ["SOCIALSCRAPE_OUTPUT_DIR"] = str(Path(args.output_dir).expanduser().resolve())
|
|
143
|
+
|
|
144
|
+
if args.interactive or not args.target:
|
|
145
|
+
run_interactive_wizard()
|
|
146
|
+
return
|
|
147
|
+
|
|
148
|
+
parsed = extract_threads_target(args.target)
|
|
149
|
+
result = {}
|
|
150
|
+
|
|
151
|
+
if args.profile or (parsed["type"] == "user" and not args.feed):
|
|
152
|
+
result = get_threads_user_profile(parsed["id"])
|
|
153
|
+
elif args.feed:
|
|
154
|
+
result = get_threads_user_posts(parsed["id"], limit=args.limit)
|
|
155
|
+
elif args.post or parsed["type"] == "post":
|
|
156
|
+
result = get_thread_post_and_replies(parsed["url"])
|
|
157
|
+
if args.download_video or args.download_thumb:
|
|
158
|
+
result["media_download"] = download_threads_media(
|
|
159
|
+
parsed["url"],
|
|
160
|
+
download_video=args.download_video,
|
|
161
|
+
download_thumbnail=args.download_thumb,
|
|
162
|
+
quality=args.quality
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
if args.stdout:
|
|
166
|
+
print(json.dumps(result, indent=2, default=str))
|
|
167
|
+
else:
|
|
168
|
+
status = result.get("status")
|
|
169
|
+
if status == "success":
|
|
170
|
+
print(f"✅ Extraction completed successfully!")
|
|
171
|
+
if "saved_path" in result:
|
|
172
|
+
print(f"💾 File: {result['saved_path']}")
|
|
173
|
+
else:
|
|
174
|
+
print(f"[!] Notice: {result.get('error', 'Operation finished with warnings.')}")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
if __name__ == "__main__":
|
|
178
|
+
main()
|
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Threads Scraper Pure SDK (`core.py`)
|
|
3
|
+
Pure zero-side-effect Python SDK for Meta's Threads data extraction and media downloading.
|
|
4
|
+
Utilizes dynamic LSD token extraction and public GraphQL queries.
|
|
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
|
+
]
|
|
56
|
+
|
|
57
|
+
DEFAULT_LSD_TOKEN = "AVq_xS7vA18"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def get_random_headers(lsd_token: Optional[str] = None) -> Dict[str, str]:
|
|
61
|
+
"""Generates stealth headers for Threads requests."""
|
|
62
|
+
headers = {
|
|
63
|
+
"User-Agent": random.choice(USER_AGENTS),
|
|
64
|
+
"Accept": "*/*",
|
|
65
|
+
"Accept-Language": "en-US,en;q=0.9",
|
|
66
|
+
"Origin": "https://www.threads.net",
|
|
67
|
+
"Referer": "https://www.threads.net/",
|
|
68
|
+
"Sec-Fetch-Site": "same-origin",
|
|
69
|
+
"Sec-Fetch-Mode": "cors",
|
|
70
|
+
"Sec-Fetch-Dest": "empty",
|
|
71
|
+
"X-IG-App-ID": "238260118697367",
|
|
72
|
+
"X-FB-LSD": lsd_token or DEFAULT_LSD_TOKEN,
|
|
73
|
+
}
|
|
74
|
+
return headers
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def extract_threads_target(target: str) -> Dict[str, str]:
|
|
78
|
+
"""
|
|
79
|
+
Parses a raw Threads URL or username.
|
|
80
|
+
Supported:
|
|
81
|
+
- Post URL: https://www.threads.net/@zuck/post/C8abc123
|
|
82
|
+
- User URL: https://www.threads.net/@zuck
|
|
83
|
+
- Handle: @zuck, zuck
|
|
84
|
+
"""
|
|
85
|
+
t = target.strip()
|
|
86
|
+
if "/post/" in t:
|
|
87
|
+
match = re.search(r"/post/([a-zA-Z0-9_-]+)", t)
|
|
88
|
+
post_code = match.group(1) if match else t
|
|
89
|
+
return {"type": "post", "id": post_code, "url": t}
|
|
90
|
+
elif "threads.net/@" in t or "threads.net/u/" in t:
|
|
91
|
+
match = re.search(r"threads\.net/@([^/?#&]+)", t)
|
|
92
|
+
username = match.group(1) if match else t
|
|
93
|
+
return {"type": "user", "id": username, "url": t}
|
|
94
|
+
elif t.startswith("@"):
|
|
95
|
+
username = t.lstrip("@")
|
|
96
|
+
return {"type": "user", "id": username, "url": f"https://www.threads.net/@{username}"}
|
|
97
|
+
elif not t.startswith("http"):
|
|
98
|
+
return {"type": "user", "id": t, "url": f"https://www.threads.net/@{t}"}
|
|
99
|
+
|
|
100
|
+
return {"type": "post", "id": t, "url": t}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def get_threads_lsd_token() -> str:
|
|
104
|
+
"""
|
|
105
|
+
Extracts the dynamic LSD (Local Storage Data) CSRF token from Threads public HTML.
|
|
106
|
+
"""
|
|
107
|
+
if not HAS_REQUESTS:
|
|
108
|
+
return DEFAULT_LSD_TOKEN
|
|
109
|
+
|
|
110
|
+
try:
|
|
111
|
+
resp = requests.get(
|
|
112
|
+
"https://www.threads.net",
|
|
113
|
+
headers={"User-Agent": random.choice(USER_AGENTS)},
|
|
114
|
+
timeout=8
|
|
115
|
+
)
|
|
116
|
+
if resp.status_code == 200:
|
|
117
|
+
# Pattern 1: ["LSD",[],{"token":"..."}]
|
|
118
|
+
m = re.search(r'["\']LSD["\'],\[\],\{["\']token["\']:["\']([^"\']+)["\']\}', resp.text)
|
|
119
|
+
if m:
|
|
120
|
+
return m.group(1)
|
|
121
|
+
# Pattern 2: name="lsd" value="..."
|
|
122
|
+
m2 = re.search(r'name="lsd"\s+value="([^"]+)"', resp.text)
|
|
123
|
+
if m2:
|
|
124
|
+
return m2.group(1)
|
|
125
|
+
# Pattern 3: "LSD",token:"..."
|
|
126
|
+
m3 = re.search(r'LSD.*?token["\':\s]+([^"\'\s,]+)', resp.text)
|
|
127
|
+
if m3:
|
|
128
|
+
return m3.group(1)
|
|
129
|
+
# Pattern 4: generic LSD token match
|
|
130
|
+
m4 = re.search(r'["\']token["\']:["\']([a-zA-Z0-9_-]{8,})["\']', resp.text)
|
|
131
|
+
if m4:
|
|
132
|
+
return m4.group(1)
|
|
133
|
+
except Exception:
|
|
134
|
+
pass
|
|
135
|
+
|
|
136
|
+
return DEFAULT_LSD_TOKEN
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def get_threads_user_profile(
|
|
140
|
+
username: str,
|
|
141
|
+
output_dir: Optional[Union[Path, str]] = None
|
|
142
|
+
) -> Dict[str, Any]:
|
|
143
|
+
"""
|
|
144
|
+
Scrapes user profile information (Bio, Followers, Verified status, Profile Link, Avatar).
|
|
145
|
+
"""
|
|
146
|
+
clean_user = username.lstrip("@").strip()
|
|
147
|
+
if not HAS_REQUESTS:
|
|
148
|
+
return {"status": "error", "username": clean_user, "error": "requests library is required."}
|
|
149
|
+
|
|
150
|
+
# Enforce RateLimiter pacing
|
|
151
|
+
if HAS_SESSION_MANAGER:
|
|
152
|
+
try:
|
|
153
|
+
limiter = RateLimiter()
|
|
154
|
+
limiter.check_and_pace("threads")
|
|
155
|
+
except Exception:
|
|
156
|
+
pass
|
|
157
|
+
|
|
158
|
+
lsd = get_threads_lsd_token()
|
|
159
|
+
url = f"https://www.threads.net/@{clean_user}"
|
|
160
|
+
headers = get_random_headers(lsd)
|
|
161
|
+
|
|
162
|
+
try:
|
|
163
|
+
resp = requests.get(url, headers=headers, timeout=12)
|
|
164
|
+
if resp.status_code != 200:
|
|
165
|
+
return {
|
|
166
|
+
"status": "error",
|
|
167
|
+
"username": clean_user,
|
|
168
|
+
"error": f"Failed to fetch profile (HTTP {resp.status_code})"
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
# Parse inline JSON state
|
|
172
|
+
profile_data: Dict[str, Any] = {
|
|
173
|
+
"username": clean_user,
|
|
174
|
+
"full_name": None,
|
|
175
|
+
"bio": None,
|
|
176
|
+
"follower_count": None,
|
|
177
|
+
"is_verified": False,
|
|
178
|
+
"profile_pic_url": None,
|
|
179
|
+
"pk": None
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
# Regex for bio and user details in HTML/state
|
|
183
|
+
bio_match = re.search(r'"biography":"(.*?)"', resp.text)
|
|
184
|
+
if bio_match:
|
|
185
|
+
try:
|
|
186
|
+
profile_data["bio"] = bio_match.group(1).encode('utf-8').decode('unicode-escape')
|
|
187
|
+
except Exception:
|
|
188
|
+
profile_data["bio"] = bio_match.group(1)
|
|
189
|
+
|
|
190
|
+
name_match = re.search(r'"full_name":"(.*?)"', resp.text)
|
|
191
|
+
if name_match:
|
|
192
|
+
try:
|
|
193
|
+
profile_data["full_name"] = name_match.group(1).encode('utf-8').decode('unicode-escape')
|
|
194
|
+
except Exception:
|
|
195
|
+
profile_data["full_name"] = name_match.group(1)
|
|
196
|
+
|
|
197
|
+
pic_match = re.search(r'"profile_pic_url":"(.*?)"', resp.text)
|
|
198
|
+
if pic_match:
|
|
199
|
+
profile_data["profile_pic_url"] = pic_match.group(1).replace("\\u0026", "&")
|
|
200
|
+
|
|
201
|
+
ver_match = re.search(r'"is_verified":(true|false)', resp.text)
|
|
202
|
+
if ver_match:
|
|
203
|
+
profile_data["is_verified"] = (ver_match.group(1) == "true")
|
|
204
|
+
|
|
205
|
+
pk_match = re.search(r'"pk":"?(\d+)"?', resp.text)
|
|
206
|
+
if pk_match:
|
|
207
|
+
profile_data["pk"] = pk_match.group(1)
|
|
208
|
+
|
|
209
|
+
# Fallback to OpenGraph meta tags if needed
|
|
210
|
+
if not profile_data["full_name"]:
|
|
211
|
+
og_title = re.search(r'<meta property="og:title" content="([^"]+)"', resp.text)
|
|
212
|
+
if og_title:
|
|
213
|
+
profile_data["full_name"] = og_title.group(1).split(" (@")[0].strip()
|
|
214
|
+
|
|
215
|
+
if not profile_data["bio"]:
|
|
216
|
+
og_desc = re.search(r'<meta property="og:description" content="([^"]+)"', resp.text)
|
|
217
|
+
if og_desc:
|
|
218
|
+
profile_data["bio"] = og_desc.group(1)
|
|
219
|
+
|
|
220
|
+
if not profile_data["follower_count"]:
|
|
221
|
+
f_match = re.search(r'([0-9,.]+[KMBkmb]?)\s+[Ff]ollowers', resp.text)
|
|
222
|
+
if f_match:
|
|
223
|
+
profile_data["follower_count"] = f_match.group(1)
|
|
224
|
+
|
|
225
|
+
base_out = Path(output_dir) if output_dir else (_outputs_dir() / "text_posts" / f"user_{clean_user}")
|
|
226
|
+
base_out.mkdir(parents=True, exist_ok=True)
|
|
227
|
+
save_path = base_out / "profile.json"
|
|
228
|
+
|
|
229
|
+
with open(save_path, "w", encoding="utf-8") as f:
|
|
230
|
+
json.dump(profile_data, f, indent=2)
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
"status": "success",
|
|
234
|
+
"username": clean_user,
|
|
235
|
+
"saved_path": str(save_path),
|
|
236
|
+
"profile": profile_data
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
except Exception as e:
|
|
240
|
+
return {"status": "error", "username": clean_user, "error": str(e)}
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def get_threads_user_posts(
|
|
244
|
+
username: str,
|
|
245
|
+
limit: int = 15,
|
|
246
|
+
output_dir: Optional[Union[Path, str]] = None
|
|
247
|
+
) -> Dict[str, Any]:
|
|
248
|
+
"""
|
|
249
|
+
Fetches user's posted threads, text contents, like counts, and reply counts.
|
|
250
|
+
"""
|
|
251
|
+
clean_user = username.lstrip("@").strip()
|
|
252
|
+
if not HAS_REQUESTS:
|
|
253
|
+
return {"status": "error", "username": clean_user, "error": "requests required."}
|
|
254
|
+
|
|
255
|
+
# Enforce RateLimiter pacing
|
|
256
|
+
if HAS_SESSION_MANAGER:
|
|
257
|
+
try:
|
|
258
|
+
limiter = RateLimiter()
|
|
259
|
+
limiter.check_and_pace("threads")
|
|
260
|
+
except Exception:
|
|
261
|
+
pass
|
|
262
|
+
|
|
263
|
+
lsd = get_threads_lsd_token()
|
|
264
|
+
url = f"https://www.threads.net/@{clean_user}"
|
|
265
|
+
headers = get_random_headers(lsd)
|
|
266
|
+
|
|
267
|
+
try:
|
|
268
|
+
resp = requests.get(url, headers=headers, timeout=12)
|
|
269
|
+
if resp.status_code != 200:
|
|
270
|
+
return {"status": "error", "username": clean_user, "error": f"HTTP {resp.status_code}"}
|
|
271
|
+
|
|
272
|
+
# Extract thread items from inline JSON payload
|
|
273
|
+
posts: List[Dict[str, Any]] = []
|
|
274
|
+
text_matches = re.findall(r'"post":\{"pk":"?(\d+)"?.*?"caption":\{"text":"(.*?)"\}.*?"like_count":(\d+)', resp.text)
|
|
275
|
+
|
|
276
|
+
for m in text_matches[:limit]:
|
|
277
|
+
posts.append({
|
|
278
|
+
"id": m[0],
|
|
279
|
+
"text": m[1].encode('utf-8').decode('unicode-escape', errors='ignore'),
|
|
280
|
+
"likes": int(m[2]),
|
|
281
|
+
"author": clean_user
|
|
282
|
+
})
|
|
283
|
+
|
|
284
|
+
# If regex fallback is needed
|
|
285
|
+
if not posts:
|
|
286
|
+
captions = re.findall(r'"text":"([^"]{10,500})"', resp.text)
|
|
287
|
+
for idx, c in enumerate(captions[:limit]):
|
|
288
|
+
clean_text = c.encode('utf-8').decode('unicode-escape', errors='ignore')
|
|
289
|
+
if not any(k in clean_text for k in ["<!DOCTYPE", "window.__", "function"]):
|
|
290
|
+
posts.append({
|
|
291
|
+
"id": f"thread_{idx+1}",
|
|
292
|
+
"text": clean_text,
|
|
293
|
+
"author": clean_user
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
base_out = Path(output_dir) if output_dir else (_outputs_dir() / "text_posts" / f"user_{clean_user}")
|
|
297
|
+
base_out.mkdir(parents=True, exist_ok=True)
|
|
298
|
+
save_path = base_out / "feed.json"
|
|
299
|
+
|
|
300
|
+
with open(save_path, "w", encoding="utf-8") as f:
|
|
301
|
+
json.dump({"username": clean_user, "count": len(posts), "posts": posts}, f, indent=2)
|
|
302
|
+
|
|
303
|
+
return {
|
|
304
|
+
"status": "success",
|
|
305
|
+
"username": clean_user,
|
|
306
|
+
"count": len(posts),
|
|
307
|
+
"saved_path": str(save_path),
|
|
308
|
+
"posts": posts
|
|
309
|
+
}
|
|
310
|
+
except Exception as e:
|
|
311
|
+
return {"status": "error", "username": clean_user, "error": str(e)}
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def get_thread_post_and_replies(
|
|
315
|
+
post_url_or_code: str,
|
|
316
|
+
output_dir: Optional[Union[Path, str]] = None
|
|
317
|
+
) -> Dict[str, Any]:
|
|
318
|
+
"""
|
|
319
|
+
Extracts a specific Thread discussion, root post text, like count, and replies.
|
|
320
|
+
"""
|
|
321
|
+
parsed = extract_threads_target(post_url_or_code)
|
|
322
|
+
post_id = parsed["id"]
|
|
323
|
+
url = parsed["url"] if parsed["url"].startswith("http") else f"https://www.threads.net/post/{post_id}"
|
|
324
|
+
|
|
325
|
+
if not HAS_REQUESTS:
|
|
326
|
+
return {"status": "error", "post_id": post_id, "error": "requests required."}
|
|
327
|
+
|
|
328
|
+
# Enforce RateLimiter pacing
|
|
329
|
+
if HAS_SESSION_MANAGER:
|
|
330
|
+
try:
|
|
331
|
+
limiter = RateLimiter()
|
|
332
|
+
limiter.check_and_pace("threads")
|
|
333
|
+
except Exception:
|
|
334
|
+
pass
|
|
335
|
+
|
|
336
|
+
lsd = get_threads_lsd_token()
|
|
337
|
+
headers = get_random_headers(lsd)
|
|
338
|
+
|
|
339
|
+
try:
|
|
340
|
+
resp = requests.get(url, headers=headers, timeout=12)
|
|
341
|
+
if resp.status_code != 200:
|
|
342
|
+
return {"status": "error", "post_id": post_id, "error": f"HTTP {resp.status_code}"}
|
|
343
|
+
|
|
344
|
+
post_data = {
|
|
345
|
+
"id": post_id,
|
|
346
|
+
"url": url,
|
|
347
|
+
"text": None,
|
|
348
|
+
"author": None,
|
|
349
|
+
"likes": 0,
|
|
350
|
+
"replies": []
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
# Extract root caption
|
|
354
|
+
caption_match = re.search(r'"caption":\{"text":"(.*?)"\}', resp.text)
|
|
355
|
+
if caption_match:
|
|
356
|
+
post_data["text"] = caption_match.group(1).encode('utf-8').decode('unicode-escape', errors='ignore')
|
|
357
|
+
else:
|
|
358
|
+
og_desc = re.search(r'<meta property="og:description" content="([^"]+)"', resp.text)
|
|
359
|
+
if og_desc:
|
|
360
|
+
post_data["text"] = og_desc.group(1)
|
|
361
|
+
|
|
362
|
+
author_match = re.search(r'"username":"([^"]+)"', resp.text)
|
|
363
|
+
if author_match:
|
|
364
|
+
post_data["author"] = author_match.group(1)
|
|
365
|
+
|
|
366
|
+
base_out = Path(output_dir) if output_dir else (_outputs_dir() / "comments" / f"thread_{post_id}")
|
|
367
|
+
base_out.mkdir(parents=True, exist_ok=True)
|
|
368
|
+
save_path = base_out / "discussion.json"
|
|
369
|
+
|
|
370
|
+
with open(save_path, "w", encoding="utf-8") as f:
|
|
371
|
+
json.dump(post_data, f, indent=2)
|
|
372
|
+
|
|
373
|
+
return {
|
|
374
|
+
"status": "success",
|
|
375
|
+
"post_id": post_id,
|
|
376
|
+
"saved_path": str(save_path),
|
|
377
|
+
"discussion": post_data
|
|
378
|
+
}
|
|
379
|
+
except Exception as e:
|
|
380
|
+
return {"status": "error", "post_id": post_id, "error": str(e)}
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def download_threads_media(
|
|
384
|
+
post_url_or_code: str,
|
|
385
|
+
output_dir: Optional[Union[Path, str]] = None,
|
|
386
|
+
download_video: bool = True,
|
|
387
|
+
download_thumbnail: bool = True,
|
|
388
|
+
quality: str = "best"
|
|
389
|
+
) -> Dict[str, Any]:
|
|
390
|
+
"""
|
|
391
|
+
Downloads attached MP4 video or photo thumbnails from a Thread via yt-dlp.
|
|
392
|
+
"""
|
|
393
|
+
parsed = extract_threads_target(post_url_or_code)
|
|
394
|
+
post_id = parsed["id"]
|
|
395
|
+
url = parsed["url"] if parsed["url"].startswith("http") else f"https://www.threads.net/post/{post_id}"
|
|
396
|
+
|
|
397
|
+
if not HAS_YT_DLP:
|
|
398
|
+
return {
|
|
399
|
+
"status": "error",
|
|
400
|
+
"post_id": post_id,
|
|
401
|
+
"error": "yt-dlp is required for Threads media downloads.",
|
|
402
|
+
"video_path": None,
|
|
403
|
+
"thumbnail_path": None
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
base_out = Path(output_dir) if output_dir else (_outputs_dir() / "videos" / f"thread_{post_id}")
|
|
407
|
+
base_out.mkdir(parents=True, exist_ok=True)
|
|
408
|
+
thumb_out = _outputs_dir() / "thumbnails" / f"thread_{post_id}"
|
|
409
|
+
thumb_out.mkdir(parents=True, exist_ok=True)
|
|
410
|
+
|
|
411
|
+
result: Dict[str, Any] = {
|
|
412
|
+
"status": "success",
|
|
413
|
+
"post_id": post_id,
|
|
414
|
+
"video_path": None,
|
|
415
|
+
"thumbnail_path": None,
|
|
416
|
+
"title": None,
|
|
417
|
+
"error": None
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
try:
|
|
421
|
+
if download_thumbnail:
|
|
422
|
+
ydl_thumb_opts = {
|
|
423
|
+
"skip_download": True,
|
|
424
|
+
"writethumbnail": True,
|
|
425
|
+
"outtmpl": str(thumb_out / "thumbnail.%(ext)s"),
|
|
426
|
+
"quiet": True,
|
|
427
|
+
"no_warnings": True,
|
|
428
|
+
}
|
|
429
|
+
with yt_dlp.YoutubeDL(ydl_thumb_opts) as ydl:
|
|
430
|
+
info = ydl.extract_info(url, download=True)
|
|
431
|
+
result["title"] = info.get("title")
|
|
432
|
+
for ext in ["jpg", "jpeg", "png", "webp"]:
|
|
433
|
+
p = thumb_out / f"thumbnail.{ext}"
|
|
434
|
+
if p.exists():
|
|
435
|
+
result["thumbnail_path"] = str(p)
|
|
436
|
+
break
|
|
437
|
+
|
|
438
|
+
if download_video:
|
|
439
|
+
format_spec = "bestvideo+bestaudio/best" if quality == "best" else f"bestvideo[height<={quality.rstrip('p')}]+bestaudio/best[height<={quality.rstrip('p')}]"
|
|
440
|
+
ydl_video_opts = {
|
|
441
|
+
"format": format_spec,
|
|
442
|
+
"outtmpl": str(base_out / "video.%(ext)s"),
|
|
443
|
+
"quiet": True,
|
|
444
|
+
"no_warnings": True,
|
|
445
|
+
"merge_output_format": "mp4",
|
|
446
|
+
}
|
|
447
|
+
with yt_dlp.YoutubeDL(ydl_video_opts) as ydl:
|
|
448
|
+
info = ydl.extract_info(url, download=True)
|
|
449
|
+
result["title"] = info.get("title", result["title"])
|
|
450
|
+
for ext in ["mp4", "mkv", "webm"]:
|
|
451
|
+
p = base_out / f"video.{ext}"
|
|
452
|
+
if p.exists():
|
|
453
|
+
result["video_path"] = str(p)
|
|
454
|
+
break
|
|
455
|
+
|
|
456
|
+
except Exception as e:
|
|
457
|
+
result["status"] = "partial" if (result["video_path"] or result["thumbnail_path"]) else "error"
|
|
458
|
+
result["error"] = str(e)
|
|
459
|
+
|
|
460
|
+
return result
|