返回 last30days-skill
xquik.py
根目录 / skills / last30days / scripts / lib / xquik.py
1 """Xquik X search source for the v3.0.0 last30days pipeline.
2
3 Uses the Xquik REST API (https://xquik.com/api/v1) to search X/Twitter
4 with full engagement metrics (likes, retweets, replies, quotes, views,
5 bookmarks). Requires an API key from xquik.com.
6 """
7
8 from __future__ import annotations
9
10 import re
11 import time
12 from datetime import datetime, timezone
13 from typing import Any, Dict, List, Optional
14
15 from . import health, http, log
16 from .dates import x_date_filters
17 from .relevance import token_overlap_relevance as _compute_relevance
18 from .x_api import _clean_handle, is_own_post
19
20 # Per-process probe cache: (state, reason). state is "unset" until probed, then
21 # True (funded/working) | False (auth/payment failure) | None (inconclusive).
22 _probe_cache: tuple = ("unset", "")
23
24 # Depth configurations: number of results to request per query
25 DEPTH_CONFIG = {
26 "quick": {"limit": 10, "queries": 1},
27 "default": {"limit": 20, "queries": 2},
28 "deep": {"limit": 40, "queries": 3},
29 }
30
31 _BASE_URL = "https://xquik.com/api/v1"
32
33
34 def _log(msg: str):
35 log.source_log("Xquik", msg, tty_only=False)
36
37
38 def _extract_core_subject(topic: str) -> str:
39 """Extract core subject for X search queries."""
40 from .query import extract_core_subject
41 return extract_core_subject(topic, max_words=5, strip_suffixes=True)
42
43
44 _CONTROL_CHARS_RE = re.compile(r"[\x00-\x1f\x7f]")
45 _MAX_TWEET_ID_DIGITS = 20
46
47
48 def _clean_tweet_id(value: Any) -> str:
49 """Return a positive ASCII numeric tweet id, or '' when invalid."""
50 if value is None or isinstance(value, bool):
51 return ""
52 if isinstance(value, int):
53 if value <= 0 or value.bit_length() > 67:
54 return ""
55 candidate = str(value)
56 elif isinstance(value, str):
57 candidate = value.strip()
58 else:
59 return ""
60 if len(candidate) > _MAX_TWEET_ID_DIGITS or not (candidate.isascii() and candidate.isdigit()):
61 return ""
62 return candidate if candidate.lstrip("0") else ""
63
64
65 def _sanitize_topic_query(query_text: str) -> str:
66 """Sanitize a topic query before appending engine-owned date filters.
67
68 Neutralizes backslashes, balances quotes and parentheses, drops unquoted X
69 search operators (colon-containing tokens and leading-``-`` negations,
70 preserving trailing-colon subject punctuation), drops empty groups or
71 dangling ``OR`` operators, and parenthesizes top-level ``OR`` expressions
72 so trailing date filters apply to every branch.
73 """
74 if not isinstance(query_text, str):
75 return ""
76 cleaned = _CONTROL_CHARS_RE.sub(
77 " ",
78 query_text.replace("\\", " ").replace("“", '"').replace("”", '"'),
79 ).strip()
80 if not cleaned:
81 return ""
82
83 chars = list(cleaned)
84 in_quote = False
85 open_quote_idx = -1
86 for i, ch in enumerate(chars):
87 if ch == '"':
88 if in_quote:
89 in_quote = False
90 open_quote_idx = -1
91 else:
92 in_quote = True
93 open_quote_idx = i
94 if in_quote and open_quote_idx >= 0:
95 chars[open_quote_idx] = " "
96
97 in_quote = False
98 paren_stack: List[int] = []
99 for i, ch in enumerate(chars):
100 if ch == '"':
101 in_quote = not in_quote
102 elif not in_quote:
103 if ch == "(":
104 paren_stack.append(i)
105 elif ch == ")":
106 if paren_stack:
107 paren_stack.pop()
108 else:
109 chars[i] = " "
110 for idx in paren_stack:
111 chars[idx] = " "
112
113 balanced = "".join(chars)
114 tokens: List[str] = []
115 i = 0
116 n = len(balanced)
117 while i < n:
118 ch = balanced[i]
119 if ch.isspace():
120 i += 1
121 continue
122 if ch == '"':
123 end = balanced.find('"', i + 1)
124 if end == -1:
125 break
126 inner = " ".join(balanced[i + 1:end].split())
127 if inner:
128 tokens.append(f'"{inner}"')
129 i = end + 1
130 continue
131 if ch in ("(", ")"):
132 tokens.append(ch)
133 i += 1
134 continue
135 start = i
136 while i < n and not balanced[i].isspace() and balanced[i] not in ('"', "(", ")"):
137 i += 1
138 word = balanced[start:i]
139 if word.endswith(":") and word.count(":") == 1:
140 word = word[:-1]
141 if not word or ":" in word or word.startswith("-"):
142 continue
143 tokens.append(word)
144
145 changed = True
146 while changed and tokens:
147 changed = False
148 pruned: List[str] = []
149 idx = 0
150 while idx < len(tokens):
151 tok = tokens[idx]
152 if tok == "(" and idx + 1 < len(tokens) and tokens[idx + 1] == ")":
153 idx += 2
154 changed = True
155 continue
156 if tok == "OR":
157 prev = pruned[-1] if pruned else None
158 nxt = tokens[idx + 1] if idx + 1 < len(tokens) else None
159 if prev in (None, "(", "OR") or nxt in (None, ")", "OR"):
160 idx += 1
161 changed = True
162 continue
163 pruned.append(tok)
164 idx += 1
165 tokens = pruned
166
167 if not tokens:
168 return ""
169
170 depth = 0
171 has_top_level_or = False
172 parts: List[str] = []
173 for tok in tokens:
174 if tok == "(":
175 depth += 1
176 if parts and parts[-1] != "(":
177 parts.append(" ")
178 parts.append("(")
179 elif tok == ")":
180 depth = max(0, depth - 1)
181 parts.append(")")
182 else:
183 if tok == "OR" and depth == 0:
184 has_top_level_or = True
185 if parts and parts[-1] != "(":
186 parts.append(" ")
187 parts.append(tok)
188
189 reconstructed = "".join(parts).strip()
190 if not reconstructed:
191 return ""
192 if has_top_level_or:
193 return f"({reconstructed})"
194 return reconstructed
195
196
197 def expand_xquik_queries(topic: str, depth: str) -> List[str]:
198 """Generate query variants based on depth.
199
200 Args:
201 topic: Research topic
202 depth: "quick", "default", or "deep"
203
204 Returns:
205 List of query strings (1 for quick, 2 for default, 3 for deep).
206 """
207 core = _extract_core_subject(topic)
208 # Anti-bare-generic guard (#607): never let the core collapse to a single
209 # bare token when the topic carries more — a lone generic word floods X with
210 # off-topic collisions. Fall back to the full multi-word topic as the anchor.
211 topic_clean = topic.strip()
212 if len(core.split()) <= 1 and len(topic_clean.split()) > 1 and core.lower() != topic_clean.lower():
213 core = topic_clean
214 queries = [core]
215
216 # Add original topic if meaningfully different
217 if topic.lower().strip() != core.lower().strip():
218 queries.append(topic.strip())
219
220 # Add compound term variant for deep searches
221 if len(queries) < 3:
222 from .query import extract_compound_terms
223 compounds = extract_compound_terms(topic)
224 clean_compounds = [t.replace('"', "").strip() for t in compounds[:3] if t.replace('"', "").strip()]
225 if clean_compounds:
226 or_parts = " OR ".join(f'"{t}"' for t in clean_compounds)
227 queries.append(f"({or_parts})")
228
229 cap = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])["queries"]
230 return queries[:cap]
231
232
233 def search_xquik(
234 topic: str,
235 from_date: str,
236 to_date: str,
237 depth: str = "default",
238 token: str = "",
239 deadline: float | None = None,
240 cancel: Any = None,
241 ) -> Dict[str, Any]:
242 """Search X via Xquik REST API.
243
244 Args:
245 topic: Search topic
246 from_date: Start date (YYYY-MM-DD)
247 to_date: Inclusive end date (YYYY-MM-DD)
248 depth: Research depth - "quick", "default", or "deep"
249 token: Xquik API key
250 deadline: Optional shared wall-clock deadline (``time.monotonic()``
251 instant) from the X backend chain. Queries past the deadline are
252 never started; the per-request timeout/retry pair still bounds
253 each call (mirrors ``x_api``'s TIMEOUT_SECONDS/RETRIES pattern).
254
255 Returns:
256 Dict with "items" list and optional "error" string.
257 """
258 if not token:
259 return {"items": [], "error": "No XQUIK_API_KEY configured"}
260
261 cfg = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
262 queries = expand_xquik_queries(topic, depth)
263 all_items: List[Dict[str, Any]] = []
264 seen_ids: set[str] = set()
265 failures: List[str] = []
266 failure_states: List[tuple[str, str]] = []
267 stop_reasons: List[str] = []
268 window = (from_date, to_date)
269 date_filters = x_date_filters(from_date, to_date)
270
271 for query_text in queries:
272 if (cancel is not None and cancel.is_set()) or (deadline is not None and time.monotonic() >= deadline):
273 _log("chain deadline reached; skipping remaining queries")
274 return {"items": all_items, "error": "Xquik research cancelled or timed out"}
275 safe_query = _sanitize_topic_query(query_text)
276 if not safe_query:
277 continue
278 q = f"{safe_query} {date_filters}"
279 items, auth_error = _execute_search(
280 q, cfg["limit"], token,
281 label=safe_query, id_prefix="XQ",
282 seen_ids=seen_ids, relevance_query=query_text,
283 index_offset=len(all_items),
284 deadline_monotonic=deadline,
285 failure_out=failures,
286 failure_states_out=failure_states,
287 stop_reasons=stop_reasons,
288 max_429_retries=1,
289 include_label_in_failure=False,
290 cancel=cancel,
291 window=window,
292 )
293 if auth_error:
294 # Auth/payment failure is fatal for the whole source (e.g. 401/403,
295 # and 402-unpaid surfaced via U5 diagnose) — return it so the caller
296 # settles honestly instead of silently empty.
297 return {"items": [], "error": auth_error}
298 all_items.extend(items)
299 if stop_reasons:
300 if "rate_limited" in stop_reasons:
301 _log("rate limited (HTTP 429); skipping remaining queries")
302 break
303
304 if (cancel is not None and cancel.is_set()) or (deadline is not None and time.monotonic() >= deadline):
305 return {"items": all_items, "error": "Xquik research cancelled or timed out"}
306 if not all_items and (failure_states or failures):
307 if failure_states:
308 _, winning_error = min(
309 failure_states,
310 key=lambda pair: health.FAILURE_SPECIFICITY.get(pair[0], 9),
311 )
312 else:
313 winning_error = failures[0]
314 return {"items": [], "error": winning_error}
315 return {"items": all_items}
316
317
318 def _execute_search(
319 q: str,
320 limit: int,
321 token: str,
322 *,
323 label: str,
324 id_prefix: str,
325 seen_ids: set[str],
326 relevance_query: str,
327 index_offset: int = 0,
328 deadline_monotonic: float | None = None,
329 failure_out: Optional[List[str]] = None,
330 failure_states_out: Optional[List[tuple[str, str]]] = None,
331 stop_reasons: Optional[List[str]] = None,
332 max_429_retries: Optional[int] = None,
333 include_label_in_failure: bool = True,
334 cancel: Any = None,
335 window: Optional[tuple[str, str]] = None,
336 ) -> tuple[List[Dict[str, Any]], str | None]:
337 """Run one Xquik search call and parse its tweets.
338
339 Returns ``(items, auth_error)``. ``auth_error`` is a non-empty string only
340 on a fatal auth/payment failure (401/403); transient/HTTP errors log and
341 return ``([], None)`` so one bad lane never discards another's results.
342
343 Non-fatal failures (429, 5xx, network error, unparseable payload) append a
344 reason to ``failure_out`` instead. They stay out of the return value
345 because the caller must keep going to the next handle, but a caller that
346 stopped there would report the lane as empty rather than as failed.
347 ``relevance_query`` (the topic) is what items are scored against — for the
348 handle lanes that differs from the search query (``from:handle``).
349 ``index_offset`` keeps item ids unique across multiple calls that share an
350 accumulator (multi-query topic search, per-handle lanes).
351 ``deadline_monotonic`` bounds the request including retries at the
352 transport (mirrors ``x_api._get``).
353 """
354 label_suffix = f" for '{label}'" if include_label_in_failure else ""
355
356 def _record_failure(state: str, msg: str) -> None:
357 if failure_out is not None:
358 failure_out.append(msg)
359 if failure_states_out is not None:
360 failure_states_out.append((state, msg))
361
362 full_url = f"{_BASE_URL}/x/tweets/search?q={_url_encode(q)}&queryType=Top&limit={limit}"
363 _log(f"Searching: {label}")
364 try:
365 request_headers = {"X-Api-Key": token}
366 get_kwargs: Dict[str, Any] = {
367 "headers": request_headers,
368 "timeout": 30,
369 "retries": 2,
370 "deadline_monotonic": deadline_monotonic,
371 "cancel": cancel,
372 }
373 if max_429_retries is not None:
374 get_kwargs["max_429_retries"] = max_429_retries
375 response = http.get(full_url, **get_kwargs)
376 except http.HTTPError as exc:
377 status = getattr(exc, "status_code", None)
378 if status == 402:
379 # Unpaid key — fatal for the source, and surfaced on the real search
380 # path (not just --diagnose) so a live run reports it instead of
381 # settling silently empty. The X retrieval branch classifies by
382 # message text only, so the detail carries the "payment required"
383 # marker that http.classify_failure maps to PAYMENT_REQUIRED.
384 return [], "Xquik key unpaid: payment required (402)"
385 if status in (401, 403):
386 return [], f"Xquik auth failed ({status})"
387 _log(f"HTTP error for '{label}': {exc}")
388 if status == 429:
389 exc_text = str(exc)
390 lowered = exc_text.lower()
391 has_rate_limit_marker = any(
392 marker in lowered
393 for marker in ("http 429", "status 429", "rate limit", "too many requests")
394 )
395 msg = (
396 f"Xquik HTTP error{label_suffix}: {exc_text}"
397 if has_rate_limit_marker
398 else f"Xquik HTTP 429 rate limit{label_suffix}: {exc_text}"
399 )
400 _record_failure(health.RATE_LIMITED, msg)
401 if stop_reasons is not None:
402 stop_reasons.append("rate_limited")
403 return [], None
404 if isinstance(exc, http.DeadlineExceeded):
405 _record_failure(health.TIMEOUT, f"Xquik timed out{label_suffix}: {exc}")
406 if stop_reasons is not None:
407 stop_reasons.append("deadline")
408 return [], None
409 exc_state = getattr(exc, "outcome_state", None)
410 if exc_state == health.TIMEOUT:
411 exc_text = str(exc)
412 lowered = exc_text.lower()
413 msg = (
414 f"Xquik HTTP error{label_suffix}: {exc_text}"
415 if "timed out" in lowered or "timeout" in lowered
416 else f"Xquik timed out{label_suffix}: {exc_text}"
417 )
418 _record_failure(health.TIMEOUT, msg)
419 return [], None
420 state = exc_state or http.classify_failure(status_code=status, message=str(exc))
421 _record_failure(state, f"Xquik HTTP error{label_suffix}: {exc}")
422 return [], None
423 except Exception as exc:
424 _log(f"Error for '{label}': {exc}")
425 exc_text = str(exc)
426 lowered = exc_text.lower()
427 if isinstance(exc, TimeoutError):
428 msg = (
429 f"Xquik request failed{label_suffix}: {exc_text}"
430 if "timed out" in lowered or "timeout" in lowered
431 else f"Xquik timed out{label_suffix}: {exc_text or 'TimeoutError'}"
432 )
433 _record_failure(health.TIMEOUT, msg)
434 elif isinstance(exc, OSError):
435 _record_failure(health.UNREACHABLE, f"Xquik request failed{label_suffix}: {exc}")
436 else:
437 _record_failure(
438 http.classify_failure(message=exc_text),
439 f"Xquik request failed{label_suffix}: {exc}",
440 )
441 return [], None
442
443 if not isinstance(response, dict):
444 _log(f"Unexpected response payload for '{label}' (got {type(response).__name__})")
445 _record_failure(
446 health.SCHEMA_DRIFT,
447 f"Xquik returned unexpected payload{label_suffix} "
448 f"(got {type(response).__name__})",
449 )
450 return [], None
451
452 tweets = response.get("tweets", [])
453 if not isinstance(tweets, list):
454 _record_failure(
455 health.SCHEMA_DRIFT,
456 f"Xquik returned no tweets array{label_suffix} "
457 f"(got {type(tweets).__name__})",
458 )
459 return [], None
460 items: List[Dict[str, Any]] = []
461 for tweet in tweets:
462 if not isinstance(tweet, dict):
463 continue
464 tweet_id = _clean_tweet_id(tweet.get("id"))
465 if not tweet_id or tweet_id in seen_ids:
466 continue
467 item = _parse_tweet(
468 tweet,
469 index_offset + len(items),
470 relevance_query,
471 id_prefix=id_prefix,
472 window=window,
473 )
474 if item:
475 seen_ids.add(tweet_id)
476 items.append(item)
477 return items, None
478
479
480 # True when a tweet URL is authored by ``handle`` (their own post). Used by
481 # the ABOUT lane to drop the subject's own tweets so only mentions *by
482 # others* remain; the implementation is ``x_api.is_own_post``.
483 _is_own = is_own_post
484
485
486 def _validated_handle(raw: Any, lane: str) -> str:
487 """Validate an X handle against X's handle grammar before query interpolation."""
488 if not isinstance(raw, str):
489 _log(f"Skipping invalid non-string handle in {lane} lane")
490 return ""
491 handle = _clean_handle(raw)
492 if not handle:
493 _log(f"Skipping invalid handle in {lane} lane")
494 return handle
495
496
497 def search_handles(
498 handles: List[str],
499 topic: str,
500 from_date: str,
501 to_date: str,
502 *,
503 count_per: int = 8,
504 token: str = "",
505 failure_out: Optional[List[str]] = None,
506 deadline: float | None = None,
507 cancel: Any = None,
508 ) -> List[Dict[str, Any]]:
509 """FROM lane: tweets authored BY each handle (their own timeline).
510
511 The topic is NOT AND'd into the query (that was the from:-AND bug, #610) —
512 we pull the raw timeline and use ``topic`` for relevance ranking only.
513 Returns a flat list of item dicts (mirrors ``bird_x.search_handles``).
514
515 When ``failure_out`` is provided, any failure reason is appended — the
516 fatal auth/payment one that stops the lane, and the per-handle transient
517 ones (429, 5xx, network, unparseable payload) that do not — so the caller
518 can distinguish a failed request from a handle that posted nothing.
519 """
520 if not token or not handles:
521 return []
522 items: List[Dict[str, Any]] = []
523 seen_ids: set[str] = set()
524 seen_handles: set[str] = set()
525 window = (from_date, to_date)
526 date_filters = x_date_filters(from_date, to_date)
527 for raw in handles:
528 if (cancel is not None and cancel.is_set()) or (deadline is not None and time.monotonic() >= deadline):
529 if failure_out is not None:
530 failure_out.append("Xquik research cancelled or timed out")
531 break
532 handle = _validated_handle(raw, "from:")
533 if not handle:
534 continue
535 handle_key = handle.lower()
536 if handle_key in seen_handles:
537 continue
538 seen_handles.add(handle_key)
539 q = f"from:{handle} {date_filters}"
540 got, auth_error = _execute_search(
541 q, count_per, token,
542 label=f"from:{handle}", id_prefix="XF",
543 seen_ids=seen_ids, relevance_query=topic,
544 index_offset=len(items),
545 failure_out=failure_out,
546 deadline_monotonic=deadline,
547 cancel=cancel,
548 window=window,
549 )
550 if auth_error:
551 # Fatal auth/payment failure — stop, keep what we have. Surface the
552 # reason: an empty FROM lane is otherwise indistinguishable from a
553 # subject who simply did not post.
554 if failure_out is not None:
555 failure_out.append(auth_error)
556 break
557 items.extend(got)
558 return items
559
560
561 def search_mentions(
562 handles: List[str],
563 from_date: str,
564 to_date: str,
565 *,
566 topic: str = "",
567 count_per: int = 5,
568 token: str = "",
569 failure_out: Optional[List[str]] = None,
570 deadline: float | None = None,
571 cancel: Any = None,
572 ) -> List[Dict[str, Any]]:
573 """ABOUT lane: tweets mentioning each handle, authored by OTHERS.
574
575 Queries ``@handle -from:handle`` then drops the handle's own tweets
576 (``_is_own``) so only third-party mentions remain. Returns a flat list of
577 item dicts.
578
579 When ``failure_out`` is provided, any failure reason is appended — the
580 fatal auth/payment one that stops the lane, and the per-handle transient
581 ones (429, 5xx, network, unparseable payload) that do not — so the caller
582 can distinguish a failed request from a handle nobody mentioned.
583 """
584 if not token or not handles:
585 return []
586 items: List[Dict[str, Any]] = []
587 seen_ids: set[str] = set()
588 seen_handles: set[str] = set()
589 window = (from_date, to_date)
590 date_filters = x_date_filters(from_date, to_date)
591 for raw in handles:
592 if (cancel is not None and cancel.is_set()) or (deadline is not None and time.monotonic() >= deadline):
593 if failure_out is not None:
594 failure_out.append("Xquik research cancelled or timed out")
595 break
596 handle = _validated_handle(raw, "@")
597 if not handle:
598 continue
599 handle_key = handle.lower()
600 if handle_key in seen_handles:
601 continue
602 seen_handles.add(handle_key)
603 q = f"@{handle} -from:{handle} {date_filters}"
604 got, auth_error = _execute_search(
605 q, count_per, token,
606 label=f"@{handle}", id_prefix="XA",
607 seen_ids=seen_ids, relevance_query=topic,
608 index_offset=len(items),
609 failure_out=failure_out,
610 deadline_monotonic=deadline,
611 cancel=cancel,
612 window=window,
613 )
614 if auth_error:
615 if failure_out is not None:
616 failure_out.append(auth_error)
617 break
618 items.extend(it for it in got if not _is_own(it.get("url", ""), handle))
619 return items
620
621
622 def probe_works(token: str, timeout: int = 8) -> Optional[bool]:
623 """Cheap runtime check that the xquik key actually returns data.
624
625 Mirrors ``bird_x.probe_works`` for the key-based X path so ``--diagnose``
626 reflects reality instead of static key presence. Returns True
627 (funded/working), False (a clear auth/payment failure — 401/403, or 402
628 when the key is configured but unpaid), or None (inconclusive: timeout /
629 transient HTTP) so callers fail open.
630 The human-readable reason is available via ``probe_reason()``. Cached per
631 process so repeated diagnose calls don't re-probe.
632 """
633 global _probe_cache
634 if _probe_cache[0] != "unset":
635 return _probe_cache[0]
636 if not token:
637 _probe_cache = (False, "no XQUIK_API_KEY configured")
638 return False
639 from datetime import timedelta, timezone
640 since = (datetime.now(timezone.utc) - timedelta(days=30)).strftime("%Y-%m-%d")
641 # @x (the platform's own account) posts frequently, so a no-error response
642 # means the key works even if this particular window is quiet.
643 q = f"from:x since:{since}"
644 full_url = f"{_BASE_URL}/x/tweets/search?q={_url_encode(q)}&queryType=Top&limit=1"
645 try:
646 request_headers = {"X-Api-Key": token}
647 http.get(full_url, headers=request_headers, timeout=timeout, retries=0)
648 except http.HTTPError as exc:
649 status = getattr(exc, "status_code", None)
650 if status == 402:
651 _probe_cache = (False, "xquik key unpaid: payment required (402)")
652 elif status in (401, 403):
653 _probe_cache = (False, f"xquik auth failed ({status})")
654 else:
655 # 5xx / unexpected status — inconclusive, don't report a false-down.
656 _probe_cache = (None, f"xquik probe inconclusive ({status})")
657 return _probe_cache[0]
658 except Exception as exc:
659 _probe_cache = (None, f"xquik probe inconclusive ({type(exc).__name__})")
660 return None
661 _probe_cache = (True, "ok")
662 return True
663
664
665 def probe_reason() -> str:
666 """Human-readable reason for the last ``probe_works`` result (or '')."""
667 return _probe_cache[1]
668
669
670 def search_and_enrich(
671 topic: str,
672 from_date: str,
673 to_date: str,
674 depth: str = "default",
675 token: str = "",
676 ) -> Dict[str, Any]:
677 """Search X via Xquik and return results.
678
679 Xquik API returns full engagement data by default, so no separate
680 enrichment step is needed.
681 """
682 return search_xquik(topic, from_date, to_date, depth=depth, token=token)
683
684
685 def parse_xquik_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:
686 """Extract items from search response.
687
688 Args:
689 response: Response dict from search_xquik()
690
691 Returns:
692 List of normalized item dicts.
693 """
694 if not isinstance(response, dict):
695 return []
696 items = response.get("items", [])
697 return items if isinstance(items, list) else []
698
699
700 def _parse_tweet(
701 tweet: Dict[str, Any],
702 index: int,
703 query: str,
704 id_prefix: str = "XQ",
705 window: Optional[tuple[str, str]] = None,
706 ) -> Dict[str, Any] | None:
707 """Parse a single tweet from the API response into the standard item format."""
708 if not isinstance(tweet, dict):
709 return None
710 author = tweet.get("author")
711 if not isinstance(author, dict):
712 return None
713 raw_username = author.get("username")
714 username = _clean_handle(raw_username) if isinstance(raw_username, str) else ""
715 tweet_id = _clean_tweet_id(tweet.get("id"))
716 if not username or not tweet_id:
717 return None
718 url = f"https://x.com/{username}/status/{tweet_id}"
719
720 # Parse date
721 date = None
722 created_at = tweet.get("createdAt")
723 if isinstance(created_at, str) and created_at:
724 try:
725 if len(created_at) > 10 and created_at[10] == "T":
726 dt = datetime.fromisoformat(created_at.replace("Z", "+00:00"))
727 else:
728 dt = datetime.strptime(created_at, "%a %b %d %H:%M:%S %z %Y")
729 if dt.tzinfo is not None:
730 dt = dt.astimezone(timezone.utc)
731 date = dt.strftime("%Y-%m-%d")
732 except (ValueError, TypeError):
733 pass
734
735 if window is not None and date:
736 window_from, window_to = window
737 if window_from and date < window_from:
738 return None
739 if window_to and date > window_to:
740 return None
741
742 text = str(tweet.get("text") or "").strip()[:500]
743
744 # Leading-run @mentions = who the post is directed at (reply target). Shared
745 # parser with bird so the first-party interaction signal fires for xquik too.
746 from .query import leading_mentions
747 mentioned_handles = leading_mentions(text)
748
749 # Build engagement dict with full metrics
750 engagement = {
751 "likes": _safe_int(tweet.get("likeCount")),
752 "reposts": _safe_int(tweet.get("retweetCount")),
753 "replies": _safe_int(tweet.get("replyCount")),
754 "quotes": _safe_int(tweet.get("quoteCount")),
755 "views": _safe_int(tweet.get("viewCount")),
756 "bookmarks": _safe_int(tweet.get("bookmarkCount")),
757 }
758
759 return {
760 "id": f"{id_prefix}{index + 1}",
761 "text": text,
762 "url": url,
763 "author_handle": username,
764 "date": date,
765 "engagement": engagement,
766 "mentioned_handles": mentioned_handles,
767 "relevance": _compute_relevance(query, text) if query else 0.7,
768 "why_relevant": "",
769 }
770
771
772 def _safe_int(value: Any) -> int | None:
773 """Convert value to int, returning None on failure."""
774 if value is None or isinstance(value, bool):
775 return None
776 try:
777 return int(value)
778 except (ValueError, TypeError):
779 return None
780
781
782 def _url_encode(text: str) -> str:
783 """URL-encode a string using stdlib."""
784 from urllib.parse import quote
785 return quote(text, safe="")
786
786 lines PYTHON