| 1 | """Threads keyword search via ScrapeCreators API for /last30days. |
| 2 | |
| 3 | Uses ScrapeCreators REST API to search Threads by keyword, extracting |
| 4 | engagement metrics (likes, replies) from short text posts. |
| 5 | |
| 6 | Requires SCRAPECREATORS_API_KEY in config. Opt-in source via INCLUDE_SOURCES. |
| 7 | API docs: https://scrapecreators.com/docs |
| 8 | """ |
| 9 | |
| 10 | import math |
| 11 | import re |
| 12 | from typing import Any, Dict, List, Optional |
| 13 | |
| 14 | from . import auth_safety, dates, http, log |
| 15 | from .relevance import token_overlap_relevance as _compute_relevance |
| 16 | |
| 17 | SCRAPECREATORS_BASE = "https://api.scrapecreators.com/v1/threads" |
| 18 | |
| 19 | |
| 20 | def _sc_base() -> str: |
| 21 | if SCRAPECREATORS_BASE != "https://api.scrapecreators.com/v1/threads": |
| 22 | return SCRAPECREATORS_BASE |
| 23 | from . import env |
| 24 | return f"{env.get_scrapecreators_base_url()}/v1/threads" |
| 25 | |
| 26 | # Depth configurations: how many results to fetch |
| 27 | DEPTH_CONFIG = { |
| 28 | "quick": {"results": 10}, |
| 29 | "default": {"results": 20}, |
| 30 | "deep": {"results": 40}, |
| 31 | } |
| 32 | |
| 33 | |
| 34 | def _log(msg: str): |
| 35 | log.source_log("Threads", msg, tty_only=False) |
| 36 | |
| 37 | |
| 38 | def _extract_core_subject(topic: str) -> str: |
| 39 | """Extract core subject from verbose query for Threads search. |
| 40 | |
| 41 | The ScrapeCreators Threads keyword endpoint only returns hits for short |
| 42 | (1-2 word) queries; 3+ words or leaked boolean operators (the planner |
| 43 | emits "A OR B") return zero. Strip boolean operators and cap to the two |
| 44 | most salient words. |
| 45 | """ |
| 46 | from .query import SOCIAL_NOISE, extract_core_subject |
| 47 | core = extract_core_subject(topic, noise=SOCIAL_NOISE, max_words=2) |
| 48 | return " ".join(core.rstrip("?!.").split()[:2]) |
| 49 | |
| 50 | |
| 51 | |
| 52 | def _parse_date(item: Dict[str, Any]) -> Optional[str]: |
| 53 | """Parse date from Threads item to YYYY-MM-DD. |
| 54 | |
| 55 | Tries common timestamp fields in order: taken_at and create_time |
| 56 | (unix timestamps in Meta APIs), then created_at, published_at, and |
| 57 | date (ISO 8601 strings). dates.parse_date() handles both. |
| 58 | """ |
| 59 | for key in ("taken_at", "create_time", "created_at", "published_at", "date"): |
| 60 | val = item.get(key) |
| 61 | if val is None: |
| 62 | continue |
| 63 | dt = dates.parse_date(str(val)) |
| 64 | if dt: |
| 65 | return dt.strftime("%Y-%m-%d") |
| 66 | return None |
| 67 | |
| 68 | |
| 69 | def _parse_items(raw_items: List[Dict[str, Any]], core_topic: str) -> List[Dict[str, Any]]: |
| 70 | """Parse raw Threads items into normalized dicts.""" |
| 71 | items = [] |
| 72 | for i, raw in enumerate(raw_items): |
| 73 | if not isinstance(raw, dict): |
| 74 | continue |
| 75 | post_id = str( |
| 76 | raw.get("id") |
| 77 | or raw.get("pk") |
| 78 | or raw.get("code") |
| 79 | or f"TH{i + 1}" |
| 80 | ) |
| 81 | text = raw.get("text") or raw.get("caption") or raw.get("content") or "" |
| 82 | if isinstance(text, dict): |
| 83 | text = text.get("text", "") |
| 84 | |
| 85 | # Author extraction |
| 86 | user = raw.get("user") or raw.get("author") or {} |
| 87 | if isinstance(user, dict): |
| 88 | handle = user.get("username") or user.get("handle") or "" |
| 89 | display_name = user.get("full_name") or user.get("displayName") or handle |
| 90 | elif isinstance(user, str): |
| 91 | handle = user |
| 92 | display_name = user |
| 93 | else: |
| 94 | handle = "" |
| 95 | display_name = "" |
| 96 | |
| 97 | # Engagement metrics |
| 98 | likes = raw.get("like_count") or raw.get("likes") or 0 |
| 99 | replies = raw.get("reply_count") or raw.get("replies") or 0 |
| 100 | reposts = raw.get("repost_count") or raw.get("reposts") or 0 |
| 101 | quotes = raw.get("quote_count") or raw.get("quotes") or 0 |
| 102 | |
| 103 | date_str = _parse_date(raw) |
| 104 | |
| 105 | # Build URL |
| 106 | code = raw.get("code") or raw.get("shortcode") or "" |
| 107 | url = raw.get("url") or raw.get("share_url") or "" |
| 108 | if not url and code: |
| 109 | url = f"https://www.threads.net/post/{code}" |
| 110 | elif not url and handle and post_id: |
| 111 | url = f"https://www.threads.net/@{handle}/post/{post_id}" |
| 112 | |
| 113 | # Relevance: position-based + engagement boost (similar to bluesky) |
| 114 | rank_score = max(0.3, 1.0 - (i * 0.02)) |
| 115 | engagement_boost = min(0.2, math.log1p(likes + reposts) / 40) |
| 116 | text_relevance = _compute_relevance(core_topic, text) |
| 117 | relevance = min(1.0, text_relevance * 0.5 + rank_score * 0.3 + engagement_boost + 0.1) |
| 118 | |
| 119 | items.append({ |
| 120 | "id": post_id, |
| 121 | "handle": handle, |
| 122 | "display_name": display_name, |
| 123 | "text": text, |
| 124 | "url": url, |
| 125 | "date": date_str, |
| 126 | "engagement": { |
| 127 | "likes": likes, |
| 128 | "replies": replies, |
| 129 | "reposts": reposts, |
| 130 | "quotes": quotes, |
| 131 | }, |
| 132 | "relevance": round(relevance, 2), |
| 133 | "why_relevant": f"Threads: @{handle}: {text[:60]}" if text else f"Threads: {handle}", |
| 134 | }) |
| 135 | return items |
| 136 | |
| 137 | |
| 138 | def search_threads( |
| 139 | topic: str, |
| 140 | from_date: str, |
| 141 | to_date: str, |
| 142 | depth: str = "default", |
| 143 | token: str = None, |
| 144 | ) -> Dict[str, Any]: |
| 145 | """Search Threads via ScrapeCreators API. |
| 146 | |
| 147 | Args: |
| 148 | topic: Search topic |
| 149 | from_date: Start date (YYYY-MM-DD) |
| 150 | to_date: End date (YYYY-MM-DD) |
| 151 | depth: 'quick', 'default', or 'deep' |
| 152 | token: ScrapeCreators API key |
| 153 | |
| 154 | Returns: |
| 155 | Dict with 'items' list and optional 'error'. |
| 156 | """ |
| 157 | raw_token = token |
| 158 | clean_token, token_err = auth_safety.normalize_header_token(raw_token) |
| 159 | if token_err: |
| 160 | _log(f"ScrapeCreators error: {token_err}") |
| 161 | return {"items": [], "error": token_err} |
| 162 | if not clean_token: |
| 163 | return {"items": [], "error": "No SCRAPECREATORS_API_KEY configured"} |
| 164 | |
| 165 | config = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"]) |
| 166 | core_topic = _extract_core_subject(topic) |
| 167 | |
| 168 | _log(f"Searching for '{core_topic}' (depth={depth}, limit={config['results']})") |
| 169 | |
| 170 | try: |
| 171 | data = http.get( |
| 172 | f"{_sc_base()}/search", |
| 173 | params={"query": core_topic}, |
| 174 | headers=http.scrapecreators_headers(clean_token), |
| 175 | timeout=30, |
| 176 | retries=2, |
| 177 | ) |
| 178 | except Exception as e: |
| 179 | safe_err = auth_safety.scrub_secrets(str(e), (raw_token, clean_token)) |
| 180 | _log(f"ScrapeCreators error: {type(e).__name__}: {safe_err}") |
| 181 | return {"items": [], "error": f"{type(e).__name__}: {safe_err}"} |
| 182 | |
| 183 | # Extract items from response (try common SC response shapes) |
| 184 | raw_items = ( |
| 185 | data.get("items") |
| 186 | or data.get("data") |
| 187 | or data.get("threads") |
| 188 | or data.get("posts") |
| 189 | or data.get("search_results") |
| 190 | or [] |
| 191 | ) |
| 192 | |
| 193 | # Limit to configured count |
| 194 | raw_items = raw_items[:config["results"]] |
| 195 | |
| 196 | # Parse items |
| 197 | items = _parse_items(raw_items, core_topic) |
| 198 | |
| 199 | # Date filter |
| 200 | in_range = [i for i in items if i["date"] and from_date <= i["date"] <= to_date] |
| 201 | out_of_range = len(items) - len(in_range) |
| 202 | if in_range: |
| 203 | items = in_range |
| 204 | if out_of_range: |
| 205 | _log(f"Filtered {out_of_range} posts outside date range") |
| 206 | else: |
| 207 | _log(f"No posts within date range, keeping all {len(items)}") |
| 208 | |
| 209 | # Sort by engagement (likes) descending |
| 210 | items.sort(key=lambda x: x["engagement"]["likes"], reverse=True) |
| 211 | |
| 212 | _log(f"Found {len(items)} Threads posts") |
| 213 | return {"items": items} |
| 214 | |
| 215 | |
| 216 | def parse_threads_response(response: Dict[str, Any]) -> List[Dict[str, Any]]: |
| 217 | """Parse Threads search response to normalized format. |
| 218 | |
| 219 | Returns: |
| 220 | List of item dicts ready for normalization. |
| 221 | """ |
| 222 | return response.get("items", []) |
| 223 |