fix: harden auth flow and sync browser support docs
This commit is contained in:
@@ -36,6 +36,12 @@ def load_from_env() -> Optional[Dict[str, str]]:
|
||||
ct0 = os.environ.get("TWITTER_CT0", "")
|
||||
if auth_token and ct0:
|
||||
return {"auth_token": auth_token, "ct0": ct0}
|
||||
if auth_token or ct0:
|
||||
logger.debug(
|
||||
"Environment cookies incomplete: auth_token=%s ct0=%s",
|
||||
bool(auth_token),
|
||||
bool(ct0),
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
@@ -68,8 +74,15 @@ def verify_cookies(auth_token, ct0, cookie_string=None):
|
||||
|
||||
# Reuse the shared curl_cffi session for consistent TLS fingerprint
|
||||
session = _get_cffi_session()
|
||||
attempts = []
|
||||
|
||||
logger.debug(
|
||||
"Verifying Twitter cookies with %s cookie header",
|
||||
"full forwarded" if cookie_string else "minimal",
|
||||
)
|
||||
|
||||
for url in urls:
|
||||
endpoint = url.split("/")[-1]
|
||||
try:
|
||||
resp = session.get(url, headers=headers, timeout=5)
|
||||
if resp.status_code in (401, 403):
|
||||
@@ -78,28 +91,37 @@ def verify_cookies(auth_token, ct0, cookie_string=None):
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
data = resp.json()
|
||||
attempts.append("%s=200" % endpoint)
|
||||
logger.debug("Cookie verification succeeded via %s", endpoint)
|
||||
return {"screen_name": data.get("screen_name", "")}
|
||||
attempts.append("%s=%d" % (endpoint, resp.status_code))
|
||||
logger.debug("Verification endpoint %s returned HTTP %d, trying next...", url, resp.status_code)
|
||||
continue
|
||||
except RuntimeError:
|
||||
raise
|
||||
except Exception as e:
|
||||
attempts.append("%s=%s" % (endpoint, type(e).__name__))
|
||||
logger.debug("Verification endpoint %s failed: %s", url, e)
|
||||
continue
|
||||
|
||||
# All endpoints failed with non-auth errors — proceed without verification
|
||||
logger.info("Cookie verification skipped (no working endpoint), will verify on first API call")
|
||||
logger.info(
|
||||
"Cookie verification skipped (attempts: %s), will verify on first API call",
|
||||
", ".join(attempts) if attempts else "none",
|
||||
)
|
||||
return {}
|
||||
|
||||
|
||||
def _extract_cookies_from_jar(jar):
|
||||
# type: (Any) -> Optional[Dict[str, str]]
|
||||
def _extract_cookies_from_jar(jar, source="unknown"):
|
||||
# type: (Any, str) -> Optional[Dict[str, str]]
|
||||
"""Extract Twitter cookies from a cookie jar."""
|
||||
result = {} # type: Dict[str, str]
|
||||
all_cookies = {} # type: Dict[str, str]
|
||||
twitter_cookie_count = 0
|
||||
for cookie in jar:
|
||||
domain = cookie.domain or ""
|
||||
if _is_twitter_domain(domain):
|
||||
twitter_cookie_count += 1
|
||||
if cookie.name == "auth_token":
|
||||
result["auth_token"] = cookie.value
|
||||
elif cookie.name == "ct0":
|
||||
@@ -112,6 +134,13 @@ def _extract_cookies_from_jar(jar):
|
||||
cookies["cookie_string"] = "; ".join("%s=%s" % (k, v) for k, v in all_cookies.items())
|
||||
logger.info("Extracted %d total cookies for full browser fingerprint", len(all_cookies))
|
||||
return cookies
|
||||
logger.debug(
|
||||
"Cookie jar %s did not contain usable Twitter auth cookies (twitter_cookies=%d, auth_token=%s, ct0=%s)",
|
||||
source,
|
||||
twitter_cookie_count,
|
||||
"auth_token" in result,
|
||||
"ct0" in result,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
@@ -136,17 +165,22 @@ def _extract_in_process():
|
||||
("firefox", browser_cookie3.firefox),
|
||||
("brave", browser_cookie3.brave),
|
||||
]
|
||||
attempts = []
|
||||
|
||||
for name, fn in browsers:
|
||||
try:
|
||||
jar = fn()
|
||||
except Exception as e:
|
||||
logger.debug("%s in-process extraction failed: %s", name, e)
|
||||
attempts.append("%s=%s" % (name, type(e).__name__))
|
||||
continue
|
||||
cookies = _extract_cookies_from_jar(jar)
|
||||
cookies = _extract_cookies_from_jar(jar, source="%s(in-process)" % name)
|
||||
if cookies:
|
||||
logger.info("Found cookies in %s (in-process)", name)
|
||||
return cookies
|
||||
attempts.append("%s=no-cookies" % name)
|
||||
if attempts:
|
||||
logger.debug("In-process extraction attempts: %s", ", ".join(attempts))
|
||||
return None
|
||||
|
||||
|
||||
@@ -168,11 +202,13 @@ browsers = [
|
||||
("firefox", browser_cookie3.firefox),
|
||||
("brave", browser_cookie3.brave),
|
||||
]
|
||||
attempts = []
|
||||
|
||||
for name, fn in browsers:
|
||||
try:
|
||||
jar = fn()
|
||||
except Exception:
|
||||
except Exception as exc:
|
||||
attempts.append(f"{name}={type(exc).__name__}")
|
||||
continue
|
||||
result = {}
|
||||
all_cookies = {}
|
||||
@@ -190,8 +226,14 @@ for name, fn in browsers:
|
||||
result["all_cookies"] = all_cookies
|
||||
print(json.dumps(result))
|
||||
sys.exit(0)
|
||||
attempts.append(
|
||||
f"{name}=no-cookies(auth_token={'auth_token' in result},ct0={'ct0' in result})"
|
||||
)
|
||||
|
||||
print(json.dumps({"error": "No Twitter cookies found in any browser. Make sure you are logged into x.com."}))
|
||||
print(json.dumps({
|
||||
"error": "No Twitter cookies found in any browser. Make sure you are logged into x.com.",
|
||||
"attempts": attempts,
|
||||
}))
|
||||
sys.exit(1)
|
||||
'''
|
||||
|
||||
@@ -221,6 +263,9 @@ sys.exit(1)
|
||||
|
||||
data = json.loads(output)
|
||||
if "error" in data:
|
||||
attempts = data.get("attempts") or []
|
||||
if attempts:
|
||||
logger.debug("Subprocess extraction attempts: %s", ", ".join(str(item) for item in attempts))
|
||||
return None
|
||||
logger.info("Found cookies in %s (subprocess)", data.get("browser", "unknown"))
|
||||
|
||||
@@ -232,7 +277,17 @@ sys.exit(1)
|
||||
cookies["cookie_string"] = cookie_str
|
||||
logger.info("Extracted %d total cookies for full browser fingerprint", len(all_cookies))
|
||||
return cookies
|
||||
except (subprocess.TimeoutExpired, json.JSONDecodeError, KeyError, FileNotFoundError):
|
||||
except subprocess.TimeoutExpired:
|
||||
logger.debug("Cookie extraction subprocess timed out")
|
||||
return None
|
||||
except json.JSONDecodeError as exc:
|
||||
logger.debug("Cookie extraction subprocess returned invalid JSON: %s", exc)
|
||||
return None
|
||||
except KeyError as exc:
|
||||
logger.debug("Cookie extraction subprocess returned incomplete payload: %s", exc)
|
||||
return None
|
||||
except FileNotFoundError as exc:
|
||||
logger.debug("Cookie extraction subprocess launcher missing: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
@@ -250,11 +305,14 @@ def extract_from_browser() -> Optional[Dict[str, str]]:
|
||||
|
||||
# 2. Subprocess fallback (handles SQLite lock, but fails on macOS Keychain)
|
||||
logger.debug("In-process extraction failed, trying subprocess fallback")
|
||||
return _extract_via_subprocess()
|
||||
cookies = _extract_via_subprocess()
|
||||
if not cookies:
|
||||
logger.warning("Twitter cookie extraction failed in both in-process and subprocess modes")
|
||||
return cookies
|
||||
|
||||
|
||||
def get_cookies() -> Dict[str, str]:
|
||||
"""Get Twitter cookies. Priority: env vars -> cache file -> browser extraction.
|
||||
"""Get Twitter cookies. Priority: env vars -> browser extraction.
|
||||
|
||||
Raises RuntimeError if no cookies found.
|
||||
"""
|
||||
@@ -265,17 +323,10 @@ def get_cookies() -> Dict[str, str]:
|
||||
if cookies:
|
||||
logger.info("Loaded cookies from environment variables")
|
||||
|
||||
# 2. Try cached cookies (file cache with TTL)
|
||||
if not cookies:
|
||||
cookies = _load_cookie_cache()
|
||||
if cookies:
|
||||
logger.info("Loaded cookies from cache")
|
||||
|
||||
# 3. Try browser extraction (auto-detect)
|
||||
# 2. Try browser extraction (auto-detect)
|
||||
if not cookies:
|
||||
logger.debug("Attempting browser cookie extraction")
|
||||
cookies = extract_from_browser()
|
||||
if cookies:
|
||||
_save_cookie_cache(cookies)
|
||||
|
||||
if not cookies:
|
||||
raise RuntimeError(
|
||||
@@ -288,66 +339,12 @@ def get_cookies() -> Dict[str, str]:
|
||||
try:
|
||||
verify_cookies(cookies["auth_token"], cookies["ct0"], cookies.get("cookie_string"))
|
||||
except RuntimeError:
|
||||
# Auth failure — invalidate cache and re-extract from browser
|
||||
logger.info("Cookie verification failed, invalidating cache and re-extracting")
|
||||
invalidate_cookie_cache()
|
||||
# Auth failure — re-extract from browser and retry verification
|
||||
logger.info("Cookie verification failed, re-extracting from browser")
|
||||
fresh_cookies = extract_from_browser()
|
||||
if fresh_cookies:
|
||||
_save_cookie_cache(fresh_cookies)
|
||||
# Verify fresh cookies — if this also fails, let it raise
|
||||
verify_cookies(fresh_cookies["auth_token"], fresh_cookies["ct0"], fresh_cookies.get("cookie_string"))
|
||||
return fresh_cookies
|
||||
raise
|
||||
return cookies
|
||||
|
||||
|
||||
# ── Cookie file cache ───────────────────────────────────────────────────
|
||||
|
||||
_CACHE_DIR = os.path.join(os.path.expanduser("~"), ".cache", "twitter-cli")
|
||||
_CACHE_FILE = os.path.join(_CACHE_DIR, "cookies.json")
|
||||
_CACHE_TTL_SECONDS = 24 * 3600 # 24 hours
|
||||
|
||||
|
||||
def _load_cookie_cache():
|
||||
# type: () -> Optional[Dict[str, str]]
|
||||
"""Load cookies from file cache if within TTL."""
|
||||
try:
|
||||
if not os.path.exists(_CACHE_FILE):
|
||||
return None
|
||||
import time as _time
|
||||
mtime = os.path.getmtime(_CACHE_FILE)
|
||||
if _time.time() - mtime > _CACHE_TTL_SECONDS:
|
||||
logger.debug("Cookie cache expired (>%ds)", _CACHE_TTL_SECONDS)
|
||||
return None
|
||||
with open(_CACHE_FILE, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
if isinstance(data, dict) and "auth_token" in data and "ct0" in data:
|
||||
return data
|
||||
except Exception as exc:
|
||||
logger.debug("Failed to load cookie cache: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def _save_cookie_cache(cookies):
|
||||
# type: (Dict[str, str]) -> None
|
||||
"""Save cookies to file cache."""
|
||||
try:
|
||||
os.makedirs(_CACHE_DIR, exist_ok=True)
|
||||
with open(_CACHE_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(cookies, f, ensure_ascii=False)
|
||||
# Restrict permissions — cookies are sensitive
|
||||
os.chmod(_CACHE_FILE, 0o600)
|
||||
logger.info("Saved cookies to cache (%s)", _CACHE_FILE)
|
||||
except Exception as exc:
|
||||
logger.debug("Failed to save cookie cache: %s", exc)
|
||||
|
||||
|
||||
def invalidate_cookie_cache():
|
||||
# type: () -> None
|
||||
"""Delete the cookie cache file."""
|
||||
try:
|
||||
if os.path.exists(_CACHE_FILE):
|
||||
os.remove(_CACHE_FILE)
|
||||
logger.info("Cookie cache invalidated")
|
||||
except Exception as exc:
|
||||
logger.debug("Failed to invalidate cookie cache: %s", exc)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
Read commands:
|
||||
twitter feed # home timeline (For You)
|
||||
twitter feed -t following # following feed
|
||||
twitter favorites # bookmarks
|
||||
twitter bookmarks # bookmarks
|
||||
twitter search "query" # search tweets
|
||||
twitter user elonmusk # user profile
|
||||
twitter user-posts elonmusk # user tweets
|
||||
@@ -17,19 +17,20 @@ Write commands:
|
||||
twitter post "text" # post a tweet
|
||||
twitter delete <id> # delete a tweet
|
||||
twitter like/unlike <id> # like/unlike
|
||||
twitter favorite/unfavorite <id> # bookmark/unbookmark
|
||||
twitter bookmark/unbookmark <id> # bookmark/unbookmark
|
||||
twitter retweet/unretweet <id> # retweet/unretweet
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
|
||||
import json
|
||||
|
||||
import click
|
||||
from rich.console import Console
|
||||
|
||||
@@ -50,6 +51,7 @@ from .serialization import tweets_from_json, tweets_to_json, user_profile_to_dic
|
||||
|
||||
console = Console(stderr=True)
|
||||
FEED_TYPES = ["for-you", "following"]
|
||||
SEARCH_PRODUCTS = ["Top", "Latest", "Photos", "Videos"]
|
||||
|
||||
|
||||
def _setup_logging(verbose):
|
||||
@@ -90,6 +92,20 @@ def _get_client(config=None):
|
||||
)
|
||||
|
||||
|
||||
def _exit_with_error(exc):
|
||||
# type: (RuntimeError) -> None
|
||||
console.print("[red]❌ %s[/red]" % exc)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def _run_guarded(action):
|
||||
# type: (Callable[[], Any]) -> Any
|
||||
try:
|
||||
return action()
|
||||
except RuntimeError as exc:
|
||||
_exit_with_error(exc)
|
||||
|
||||
|
||||
def _resolve_fetch_count(max_count, configured):
|
||||
# type: (Optional[int], int) -> int
|
||||
"""Resolve fetch count with bounds checks."""
|
||||
@@ -100,6 +116,35 @@ def _resolve_fetch_count(max_count, configured):
|
||||
return max(configured, 1)
|
||||
|
||||
|
||||
def _resolve_configured_count(config, max_count):
|
||||
# type: (dict, Optional[int]) -> int
|
||||
return _resolve_fetch_count(max_count, config.get("fetch", {}).get("count", 50))
|
||||
|
||||
|
||||
def _normalize_tweet_id(value):
|
||||
# type: (str) -> str
|
||||
"""Extract a numeric tweet ID from raw input or a full X/Twitter URL."""
|
||||
raw = value.strip()
|
||||
if not raw:
|
||||
raise RuntimeError("Tweet ID or URL is required")
|
||||
|
||||
parsed = urllib.parse.urlparse(raw)
|
||||
candidate = raw
|
||||
if parsed.scheme and parsed.netloc:
|
||||
path = parsed.path.rstrip("/")
|
||||
match = re.search(r"/status/(\d+)$", path)
|
||||
if not match:
|
||||
raise RuntimeError("Invalid tweet URL: %s" % value)
|
||||
candidate = match.group(1)
|
||||
else:
|
||||
candidate = raw.rstrip("/").split("/")[-1]
|
||||
candidate = candidate.split("?", 1)[0].split("#", 1)[0]
|
||||
|
||||
if not candidate.isdigit():
|
||||
raise RuntimeError("Invalid tweet ID: %s" % value)
|
||||
return candidate
|
||||
|
||||
|
||||
def _apply_filter(tweets, do_filter, config):
|
||||
# type: (List[Tweet], bool, dict) -> List[Tweet]
|
||||
"""Optionally apply tweet filtering."""
|
||||
@@ -128,15 +173,14 @@ def _fetch_and_display(fetch_fn, label, emoji, max_count, as_json, output_file,
|
||||
if config is None:
|
||||
config = load_config()
|
||||
try:
|
||||
fetch_count = _resolve_fetch_count(max_count, config.get("fetch", {}).get("count", 50))
|
||||
fetch_count = _resolve_configured_count(config, max_count)
|
||||
console.print("%s Fetching %s (%d tweets)...\n" % (emoji, label, fetch_count))
|
||||
start = time.time()
|
||||
tweets = fetch_fn(fetch_count)
|
||||
elapsed = time.time() - start
|
||||
console.print("✅ Fetched %d %s in %.1fs\n" % (len(tweets), label, elapsed))
|
||||
except RuntimeError as exc:
|
||||
console.print("[red]❌ %s[/red]" % exc)
|
||||
sys.exit(1)
|
||||
_exit_with_error(exc)
|
||||
|
||||
filtered = _apply_filter(tweets, do_filter, config)
|
||||
|
||||
@@ -176,7 +220,7 @@ def feed(feed_type, max_count, as_json, input_file, output_file, do_filter):
|
||||
tweets = _load_tweets_from_json(input_file)
|
||||
console.print(" Loaded %d tweets" % len(tweets))
|
||||
else:
|
||||
fetch_count = _resolve_fetch_count(max_count, config.get("fetch", {}).get("count", 50))
|
||||
fetch_count = _resolve_configured_count(config, max_count)
|
||||
client = _get_client(config)
|
||||
label = "following feed" if feed_type == "following" else "home timeline"
|
||||
console.print("📡 Fetching %s (%d tweets)...\n" % (label, fetch_count))
|
||||
@@ -188,8 +232,7 @@ def feed(feed_type, max_count, as_json, input_file, output_file, do_filter):
|
||||
elapsed = time.time() - start
|
||||
console.print("✅ Fetched %d tweets in %.1fs\n" % (len(tweets), elapsed))
|
||||
except RuntimeError as exc:
|
||||
console.print("[red]❌ %s[/red]" % exc)
|
||||
sys.exit(1)
|
||||
_exit_with_error(exc)
|
||||
|
||||
filtered = _apply_filter(tweets, do_filter, config)
|
||||
|
||||
@@ -216,11 +259,24 @@ def favorites(max_count, as_json, output_file, do_filter):
|
||||
# type: (Optional[int], bool, Optional[str], bool) -> None
|
||||
"""Fetch bookmarked (favorite) tweets."""
|
||||
config = load_config()
|
||||
client = _get_client(config)
|
||||
_fetch_and_display(
|
||||
lambda count: client.fetch_bookmarks(count),
|
||||
"favorites", "🔖", max_count, as_json, output_file, do_filter, config,
|
||||
)
|
||||
def _run():
|
||||
client = _get_client(config)
|
||||
_fetch_and_display(
|
||||
lambda count: client.fetch_bookmarks(count),
|
||||
"bookmarks", "🔖", max_count, as_json, output_file, do_filter, config,
|
||||
)
|
||||
_run_guarded(_run)
|
||||
|
||||
|
||||
@cli.command(name="bookmarks")
|
||||
@click.option("--max", "-n", "max_count", type=int, default=None, help="Max number of tweets to fetch.")
|
||||
@click.option("--json", "as_json", is_flag=True, help="Output as JSON.")
|
||||
@click.option("--output", "-o", "output_file", type=str, default=None, help="Save tweets to JSON file.")
|
||||
@click.option("--filter", "do_filter", is_flag=True, help="Enable score-based filtering.")
|
||||
def bookmarks(max_count, as_json, output_file, do_filter):
|
||||
# type: (Optional[int], bool, Optional[str], bool) -> None
|
||||
"""Fetch bookmarked tweets."""
|
||||
favorites.callback(max_count=max_count, as_json=as_json, output_file=output_file, do_filter=do_filter)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@@ -236,8 +292,7 @@ def user(screen_name, as_json):
|
||||
console.print("👤 Fetching user @%s..." % screen_name)
|
||||
profile = client.fetch_user(screen_name)
|
||||
except RuntimeError as exc:
|
||||
console.print("[red]❌ %s[/red]" % exc)
|
||||
sys.exit(1)
|
||||
_exit_with_error(exc)
|
||||
|
||||
if as_json:
|
||||
click.echo(json.dumps(user_profile_to_dict(profile), ensure_ascii=False, indent=2))
|
||||
@@ -248,7 +303,7 @@ def user(screen_name, as_json):
|
||||
|
||||
@cli.command("user-posts")
|
||||
@click.argument("screen_name")
|
||||
@click.option("--max", "-n", "max_count", type=int, default=20, help="Max number of tweets to fetch.")
|
||||
@click.option("--max", "-n", "max_count", type=int, default=None, help="Max number of tweets to fetch.")
|
||||
@click.option("--json", "as_json", is_flag=True, help="Output as JSON.")
|
||||
@click.option("--output", "-o", "output_file", type=str, default=None, help="Save tweets to JSON file.")
|
||||
def user_posts(screen_name, max_count, as_json, output_file):
|
||||
@@ -256,20 +311,15 @@ def user_posts(screen_name, max_count, as_json, output_file):
|
||||
"""List a user's tweets. SCREEN_NAME is the @handle (without @)."""
|
||||
screen_name = screen_name.lstrip("@")
|
||||
config = load_config()
|
||||
client = _get_client(config)
|
||||
console.print("👤 Fetching @%s's profile..." % screen_name)
|
||||
try:
|
||||
def _run():
|
||||
client = _get_client(config)
|
||||
console.print("👤 Fetching @%s's profile..." % screen_name)
|
||||
profile = client.fetch_user(screen_name)
|
||||
except RuntimeError as exc:
|
||||
console.print("[red]❌ %s[/red]" % exc)
|
||||
sys.exit(1)
|
||||
_fetch_and_display(
|
||||
lambda count: client.fetch_user_tweets(profile.id, count),
|
||||
"@%s tweets" % screen_name, "📝", max_count, as_json, output_file, False, config,
|
||||
)
|
||||
|
||||
|
||||
SEARCH_PRODUCTS = ["Top", "Latest", "Photos", "Videos"]
|
||||
_fetch_and_display(
|
||||
lambda count: client.fetch_user_tweets(profile.id, count),
|
||||
"@%s tweets" % screen_name, "📝", max_count, as_json, output_file, False, config,
|
||||
)
|
||||
_run_guarded(_run)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@@ -282,7 +332,7 @@ SEARCH_PRODUCTS = ["Top", "Latest", "Photos", "Videos"]
|
||||
default="Top",
|
||||
help="Search tab: Top, Latest, Photos, or Videos.",
|
||||
)
|
||||
@click.option("--max", "-n", "max_count", type=int, default=20, help="Max number of tweets to fetch.")
|
||||
@click.option("--max", "-n", "max_count", type=int, default=None, help="Max number of tweets to fetch.")
|
||||
@click.option("--json", "as_json", is_flag=True, help="Output as JSON.")
|
||||
@click.option("--output", "-o", "output_file", type=str, default=None, help="Save tweets to JSON file.")
|
||||
@click.option("--filter", "do_filter", is_flag=True, help="Enable score-based filtering.")
|
||||
@@ -290,16 +340,18 @@ def search(query, product, max_count, as_json, output_file, do_filter):
|
||||
# type: (str, str, int, bool, Optional[str], bool) -> None
|
||||
"""Search tweets by QUERY string."""
|
||||
config = load_config()
|
||||
client = _get_client(config)
|
||||
_fetch_and_display(
|
||||
lambda count: client.fetch_search(query, count, product),
|
||||
"'%s' (%s)" % (query, product), "🔍", max_count, as_json, output_file, do_filter, config,
|
||||
)
|
||||
def _run():
|
||||
client = _get_client(config)
|
||||
_fetch_and_display(
|
||||
lambda count: client.fetch_search(query, count, product),
|
||||
"'%s' (%s)" % (query, product), "🔍", max_count, as_json, output_file, do_filter, config,
|
||||
)
|
||||
_run_guarded(_run)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument("screen_name")
|
||||
@click.option("--max", "-n", "max_count", type=int, default=20, help="Max number of tweets to fetch.")
|
||||
@click.option("--max", "-n", "max_count", type=int, default=None, help="Max number of tweets to fetch.")
|
||||
@click.option("--json", "as_json", is_flag=True, help="Output as JSON.")
|
||||
@click.option("--output", "-o", "output_file", type=str, default=None, help="Save tweets to JSON file.")
|
||||
@click.option("--filter", "do_filter", is_flag=True, help="Enable score-based filtering.")
|
||||
@@ -308,39 +360,35 @@ def likes(screen_name, max_count, as_json, output_file, do_filter):
|
||||
"""Show tweets liked by a user. SCREEN_NAME is the @handle (without @)."""
|
||||
screen_name = screen_name.lstrip("@")
|
||||
config = load_config()
|
||||
client = _get_client(config)
|
||||
console.print("👤 Fetching @%s's profile..." % screen_name)
|
||||
try:
|
||||
def _run():
|
||||
client = _get_client(config)
|
||||
console.print("👤 Fetching @%s's profile..." % screen_name)
|
||||
profile = client.fetch_user(screen_name)
|
||||
except RuntimeError as exc:
|
||||
console.print("[red]❌ %s[/red]" % exc)
|
||||
sys.exit(1)
|
||||
_fetch_and_display(
|
||||
lambda count: client.fetch_user_likes(profile.id, count),
|
||||
"@%s likes" % screen_name, "❤️", max_count, as_json, output_file, do_filter, config,
|
||||
)
|
||||
_fetch_and_display(
|
||||
lambda count: client.fetch_user_likes(profile.id, count),
|
||||
"@%s likes" % screen_name, "❤️", max_count, as_json, output_file, do_filter, config,
|
||||
)
|
||||
_run_guarded(_run)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument("tweet_id")
|
||||
@click.option("--max", "-n", "max_count", type=int, default=20, help="Max replies to fetch.")
|
||||
@click.option("--max", "-n", "max_count", type=int, default=None, help="Max replies to fetch.")
|
||||
@click.option("--json", "as_json", is_flag=True, help="Output as JSON.")
|
||||
def tweet(tweet_id, max_count, as_json):
|
||||
# type: (str, int, bool) -> None
|
||||
"""View a tweet and its replies. TWEET_ID is the numeric tweet ID or full URL."""
|
||||
# Extract tweet ID from URL if given
|
||||
tweet_id = tweet_id.strip().rstrip("/").split("/")[-1]
|
||||
tweet_id = _normalize_tweet_id(tweet_id)
|
||||
config = load_config()
|
||||
try:
|
||||
client = _get_client(config)
|
||||
console.print("🐦 Fetching tweet %s...\n" % tweet_id)
|
||||
start = time.time()
|
||||
tweets = client.fetch_tweet_detail(tweet_id, max_count)
|
||||
tweets = client.fetch_tweet_detail(tweet_id, _resolve_configured_count(config, max_count))
|
||||
elapsed = time.time() - start
|
||||
console.print("✅ Fetched %d tweets in %.1fs\n" % (len(tweets), elapsed))
|
||||
except RuntimeError as exc:
|
||||
console.print("[red]❌ %s[/red]" % exc)
|
||||
sys.exit(1)
|
||||
_exit_with_error(exc)
|
||||
|
||||
if as_json:
|
||||
click.echo(tweets_to_json(tweets))
|
||||
@@ -356,23 +404,25 @@ def tweet(tweet_id, max_count, as_json):
|
||||
|
||||
@cli.command(name="list")
|
||||
@click.argument("list_id")
|
||||
@click.option("--max", "-n", "max_count", type=int, default=20, help="Max tweets to fetch.")
|
||||
@click.option("--max", "-n", "max_count", type=int, default=None, help="Max tweets to fetch.")
|
||||
@click.option("--json", "as_json", is_flag=True, help="Output as JSON.")
|
||||
@click.option("--filter", "do_filter", is_flag=True, help="Enable score-based filtering.")
|
||||
def list_timeline(list_id, max_count, as_json, do_filter):
|
||||
# type: (str, int, bool, bool) -> None
|
||||
"""Fetch tweets from a Twitter List. LIST_ID is the numeric list ID."""
|
||||
config = load_config()
|
||||
client = _get_client(config)
|
||||
_fetch_and_display(
|
||||
lambda count: client.fetch_list_timeline(list_id, count),
|
||||
"list %s" % list_id, "📋", max_count, as_json, None, do_filter, config,
|
||||
)
|
||||
def _run():
|
||||
client = _get_client(config)
|
||||
_fetch_and_display(
|
||||
lambda count: client.fetch_list_timeline(list_id, count),
|
||||
"list %s" % list_id, "📋", max_count, as_json, None, do_filter, config,
|
||||
)
|
||||
_run_guarded(_run)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument("screen_name")
|
||||
@click.option("--max", "-n", "max_count", type=int, default=20, help="Max users to fetch.")
|
||||
@click.option("--max", "-n", "max_count", type=int, default=None, help="Max users to fetch.")
|
||||
@click.option("--json", "as_json", is_flag=True, help="Output as JSON.")
|
||||
def followers(screen_name, max_count, as_json):
|
||||
# type: (str, int, bool) -> None
|
||||
@@ -383,14 +433,14 @@ def followers(screen_name, max_count, as_json):
|
||||
client = _get_client(config)
|
||||
console.print("👤 Fetching @%s's profile..." % screen_name)
|
||||
profile = client.fetch_user(screen_name)
|
||||
console.print("👥 Fetching followers (%d)...\n" % max_count)
|
||||
fetch_count = _resolve_configured_count(config, max_count)
|
||||
console.print("👥 Fetching followers (%d)...\n" % fetch_count)
|
||||
start = time.time()
|
||||
users = client.fetch_followers(profile.id, max_count)
|
||||
users = client.fetch_followers(profile.id, fetch_count)
|
||||
elapsed = time.time() - start
|
||||
console.print("✅ Fetched %d followers in %.1fs\n" % (len(users), elapsed))
|
||||
except RuntimeError as exc:
|
||||
console.print("[red]❌ %s[/red]" % exc)
|
||||
sys.exit(1)
|
||||
_exit_with_error(exc)
|
||||
|
||||
if as_json:
|
||||
click.echo(users_to_json(users))
|
||||
@@ -402,7 +452,7 @@ def followers(screen_name, max_count, as_json):
|
||||
|
||||
@cli.command()
|
||||
@click.argument("screen_name")
|
||||
@click.option("--max", "-n", "max_count", type=int, default=20, help="Max users to fetch.")
|
||||
@click.option("--max", "-n", "max_count", type=int, default=None, help="Max users to fetch.")
|
||||
@click.option("--json", "as_json", is_flag=True, help="Output as JSON.")
|
||||
def following(screen_name, max_count, as_json):
|
||||
# type: (str, int, bool) -> None
|
||||
@@ -413,14 +463,14 @@ def following(screen_name, max_count, as_json):
|
||||
client = _get_client(config)
|
||||
console.print("👤 Fetching @%s's profile..." % screen_name)
|
||||
profile = client.fetch_user(screen_name)
|
||||
console.print("👥 Fetching following (%d)...\n" % max_count)
|
||||
fetch_count = _resolve_configured_count(config, max_count)
|
||||
console.print("👥 Fetching following (%d)...\n" % fetch_count)
|
||||
start = time.time()
|
||||
users = client.fetch_following(profile.id, max_count)
|
||||
users = client.fetch_following(profile.id, fetch_count)
|
||||
elapsed = time.time() - start
|
||||
console.print("✅ Fetched %d following in %.1fs\n" % (len(users), elapsed))
|
||||
except RuntimeError as exc:
|
||||
console.print("[red]❌ %s[/red]" % exc)
|
||||
sys.exit(1)
|
||||
_exit_with_error(exc)
|
||||
|
||||
if as_json:
|
||||
click.echo(users_to_json(users))
|
||||
@@ -442,8 +492,7 @@ def _write_action(emoji, action_desc, client_method, tweet_id):
|
||||
getattr(client, client_method)(tweet_id)
|
||||
console.print("[green]✅ Done.[/green]")
|
||||
except RuntimeError as exc:
|
||||
console.print("[red]❌ %s[/red]" % exc)
|
||||
sys.exit(1)
|
||||
_exit_with_error(exc)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@@ -461,8 +510,7 @@ def post(text, reply_to):
|
||||
console.print("[green]✅ Tweet posted![/green]")
|
||||
console.print("🔗 https://x.com/i/status/%s" % tweet_id)
|
||||
except RuntimeError as exc:
|
||||
console.print("[red]❌ %s[/red]" % exc)
|
||||
sys.exit(1)
|
||||
_exit_with_error(exc)
|
||||
|
||||
|
||||
@cli.command(name="delete")
|
||||
@@ -514,6 +562,14 @@ def favorite(tweet_id):
|
||||
_write_action("🔖", "Bookmarking tweet", "bookmark_tweet", tweet_id)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument("tweet_id")
|
||||
def bookmark(tweet_id):
|
||||
# type: (str,) -> None
|
||||
"""Bookmark a tweet. TWEET_ID is the numeric tweet ID."""
|
||||
_write_action("🔖", "Bookmarking tweet", "bookmark_tweet", tweet_id)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument("tweet_id")
|
||||
def unfavorite(tweet_id):
|
||||
@@ -522,5 +578,13 @@ def unfavorite(tweet_id):
|
||||
_write_action("🔖", "Removing bookmark", "unbookmark_tweet", tweet_id)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument("tweet_id")
|
||||
def unbookmark(tweet_id):
|
||||
# type: (str,) -> None
|
||||
"""Remove a tweet from bookmarks. TWEET_ID is the numeric tweet ID."""
|
||||
_write_action("🔖", "Removing bookmark", "unbookmark_tweet", tweet_id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
cli()
|
||||
|
||||
Reference in New Issue
Block a user