返回 last30days-skill
truthsocial.py
根目录 / skills / last30days / scripts / lib / truthsocial.py
1 """Truth Social search via Mastodon-compatible API (requires bearer token).
2
3 Uses truthsocial.com/api/v2/search endpoint.
4 Requires TRUTHSOCIAL_TOKEN env var (bearer token from browser dev tools).
5 """
6
7 import html
8 import math
9 import re
10 import sys
11 from typing import Any, Dict, List, Optional
12
13 from . import auth_safety, http, log
14
15 TRUTHSOCIAL_SEARCH_URL = "https://truthsocial.com/api/v2/search"
16
17 DEPTH_CONFIG = {
18 "quick": 15,
19 "default": 30,
20 "deep": 60,
21 }
22
23
24 def _log(msg: str):
25 log.source_log("TruthSocial", msg, tty_only=False)
26
27
28 def _strip_html(content: str) -> str:
29 """Strip HTML tags from Truth Social post content and decode entities.
30
31 Paragraph breaks become newlines like ``<br>`` does. Entities are decoded
32 after the tags are removed, so escaped markup in the post text stays text.
33 """
34 text = re.sub(r'<br\s*/?>|</p>\s*<p[^>]*>', '\n', content)
35 text = re.sub(r'<[^>]+>', '', text)
36 return html.unescape(text).strip()
37
38
39 def _extract_core_subject(topic: str) -> str:
40 """Extract core subject from verbose query for Truth Social search."""
41 from .query import SOCIAL_NOISE, extract_core_subject
42 return extract_core_subject(topic, noise=SOCIAL_NOISE)
43
44
45 def _parse_date(status: Dict[str, Any]) -> Optional[str]:
46 """Parse date from Mastodon status to YYYY-MM-DD.
47
48 Mastodon uses ISO 8601 format in created_at field.
49 """
50 val = status.get("created_at")
51 if val and isinstance(val, str) and len(val) >= 10:
52 return val[:10]
53 return None
54
55
56 def search_truthsocial(
57 topic: str,
58 from_date: str,
59 to_date: str,
60 depth: str = "default",
61 config: Optional[Dict[str, Any]] = None,
62 ) -> Dict[str, Any]:
63 """Search Truth Social via Mastodon-compatible API.
64
65 Args:
66 topic: Search topic
67 from_date: Start date (YYYY-MM-DD)
68 to_date: End date (YYYY-MM-DD)
69 depth: 'quick', 'default', or 'deep'
70 config: Config dict with TRUTHSOCIAL_TOKEN
71
72 Returns:
73 Dict with 'statuses' list from Mastodon API response.
74 """
75 config = config or {}
76 raw_token = config.get("TRUTHSOCIAL_TOKEN", "")
77 token, token_err = auth_safety.normalize_header_token(raw_token)
78 if token_err:
79 _log(f"Search failed: {token_err}")
80 return {"statuses": [], "error": token_err}
81 if not token:
82 return {"statuses": [], "error": "Truth Social token not configured"}
83
84 count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
85 core_topic = _extract_core_subject(topic)
86
87 _log(f"Searching for '{core_topic}' (depth={depth}, limit={count})")
88
89 from urllib.parse import urlencode
90 params = {
91 "q": core_topic,
92 "type": "statuses",
93 "limit": str(min(count, 40)),
94 }
95 url = f"{TRUTHSOCIAL_SEARCH_URL}?{urlencode(params)}"
96
97 try:
98 response = http.request(
99 "GET", url,
100 headers={
101 "Authorization": f"Bearer {token}",
102 # Cloudflare 403s the skill's default User-Agent regardless of token validity (#909).
103 # Reuse http.BROWSER_USER_AGENT, as the keyless Reddit path does.
104 "User-Agent": http.BROWSER_USER_AGENT,
105 "Accept": "application/json, text/plain, */*",
106 "Accept-Language": "en-US,en;q=0.9",
107 "Referer": "https://truthsocial.com/",
108 },
109 timeout=30,
110 )
111 except http.HTTPError as e:
112 if e.status_code == 401:
113 _log("Token expired")
114 return {"statuses": [], "error": "Truth Social token expired"}
115 elif e.status_code == 403:
116 _log("Access denied (Cloudflare)")
117 return {"statuses": [], "error": "Truth Social access denied (Cloudflare)"}
118 elif e.status_code == 429:
119 _log("Rate limited")
120 return {"statuses": [], "error": "Truth Social rate limited"}
121 else:
122 safe_err = auth_safety.scrub_secrets(str(e), (raw_token, token))
123 _log(f"Search failed: {safe_err}")
124 return {"statuses": [], "error": f"Truth Social search failed: {e.status_code}"}
125 except Exception as e:
126 safe_err = auth_safety.scrub_secrets(str(e), (raw_token, token))
127 _log(f"Search failed: {type(e).__name__}: {safe_err}")
128 return {"statuses": [], "error": f"{type(e).__name__}: {safe_err}"}
129
130 statuses = response.get("statuses", [])
131 _log(f"Found {len(statuses)} posts")
132 return response
133
134
135 def parse_truthsocial_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:
136 """Parse Mastodon API response into normalized item dicts.
137
138 Returns:
139 List of item dicts ready for normalization.
140 """
141 statuses = response.get("statuses", [])
142 items = []
143
144 for i, status in enumerate(statuses):
145 content_html = status.get("content") or ""
146 text = _strip_html(content_html)
147
148 account = status.get("account") or {}
149 handle = account.get("acct") or account.get("username") or ""
150 display_name = account.get("display_name") or handle
151
152 url = status.get("url") or ""
153
154 likes = status.get("favourites_count") or 0
155 reposts = status.get("reblogs_count") or 0
156 replies = status.get("replies_count") or 0
157
158 date_str = _parse_date(status)
159
160 # Relevance: position-based (search results are ranked by relevance)
161 rank_score = max(0.3, 1.0 - (i * 0.02))
162 engagement_boost = min(0.2, math.log1p(likes + reposts) / 40)
163 relevance = min(1.0, rank_score * 0.7 + engagement_boost + 0.1)
164
165 items.append({
166 "handle": handle,
167 "display_name": display_name,
168 "text": text,
169 "url": url,
170 "date": date_str,
171 "engagement": {
172 "likes": likes,
173 "reposts": reposts,
174 "replies": replies,
175 },
176 "relevance": round(relevance, 2),
177 "why_relevant": f"Truth Social: @{handle}: {text[:60]}" if text else f"Truth Social: {handle}",
178 })
179
180 return items
181
181 lines PYTHON