twitter-cli 0.3.4__tar.gz → 0.4.1__tar.gz

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.
Files changed (28) hide show
  1. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/PKG-INFO +3 -3
  2. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/README.md +2 -2
  3. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/pyproject.toml +1 -1
  4. twitter_cli-0.4.1/tests/test_client.py +394 -0
  5. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/twitter_cli/auth.py +90 -11
  6. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/twitter_cli/client.py +83 -3
  7. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/uv.lock +1 -1
  8. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/.github/workflows/ci.yml +0 -0
  9. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/.github/workflows/publish-clawhub.yml +0 -0
  10. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/.github/workflows/publish.yml +0 -0
  11. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/.gitignore +0 -0
  12. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/LICENSE +0 -0
  13. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/SKILL.md +0 -0
  14. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/config.yaml +0 -0
  15. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/tests/conftest.py +0 -0
  16. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/tests/test_cli.py +0 -0
  17. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/tests/test_config.py +0 -0
  18. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/tests/test_config_normalization.py +0 -0
  19. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/tests/test_filter.py +0 -0
  20. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/tests/test_serialization.py +0 -0
  21. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/twitter_cli/__init__.py +0 -0
  22. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/twitter_cli/cli.py +0 -0
  23. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/twitter_cli/config.py +0 -0
  24. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/twitter_cli/constants.py +0 -0
  25. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/twitter_cli/filter.py +0 -0
  26. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/twitter_cli/formatter.py +0 -0
  27. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/twitter_cli/models.py +0 -0
  28. {twitter_cli-0.3.4 → twitter_cli-0.4.1}/twitter_cli/serialization.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: twitter-cli
3
- Version: 0.3.4
3
+ Version: 0.4.1
4
4
  Summary: A CLI for Twitter/X — feed, bookmarks, and user timeline in terminal
5
5
  Project-URL: Homepage, https://github.com/jackwener/twitter-cli
6
6
  Project-URL: Repository, https://github.com/jackwener/twitter-cli
@@ -175,7 +175,7 @@ export TWITTER_PROXY=http://127.0.0.1:7890
175
175
  export TWITTER_PROXY=socks5://127.0.0.1:1080
176
176
  ```
177
177
 
178
- Using a proxy is **strongly recommended** to avoid IP-based rate limiting.
178
+ Using a proxy can help reduce IP-based rate limiting risks.
179
179
 
180
180
  ### Configuration
181
181
 
@@ -397,7 +397,7 @@ export TWITTER_PROXY=http://127.0.0.1:7890
397
397
  export TWITTER_PROXY=socks5://127.0.0.1:1080
398
398
  ```
399
399
 
400
- **强烈建议使用代理**,避免 IP 维度的风控。
400
+ 使用代理可以降低 IP 维度的风控风险。
401
401
 
402
402
  ### 筛选算法
403
403
 
@@ -139,7 +139,7 @@ export TWITTER_PROXY=http://127.0.0.1:7890
139
139
  export TWITTER_PROXY=socks5://127.0.0.1:1080
140
140
  ```
141
141
 
142
- Using a proxy is **strongly recommended** to avoid IP-based rate limiting.
142
+ Using a proxy can help reduce IP-based rate limiting risks.
143
143
 
144
144
  ### Configuration
145
145
 
@@ -361,7 +361,7 @@ export TWITTER_PROXY=http://127.0.0.1:7890
361
361
  export TWITTER_PROXY=socks5://127.0.0.1:1080
362
362
  ```
363
363
 
364
- **强烈建议使用代理**,避免 IP 维度的风控。
364
+ 使用代理可以降低 IP 维度的风控风险。
365
365
 
366
366
  ### 筛选算法
367
367
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "twitter-cli"
7
- version = "0.3.4"
7
+ version = "0.4.1"
8
8
  description = "A CLI for Twitter/X — feed, bookmarks, and user timeline in terminal"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -0,0 +1,394 @@
1
+ """Unit tests for core client.py functions.
2
+
3
+ Tests the parsing, header building, media extraction, Chrome target detection,
4
+ and feature flag update logic — all without requiring network access.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ from unittest.mock import MagicMock, patch
11
+
12
+
13
+ from twitter_cli.client import (
14
+ FEATURES,
15
+ _best_chrome_target,
16
+ _build_graphql_url,
17
+ _deep_get,
18
+ _extract_cursor,
19
+ _extract_media,
20
+ _parse_int,
21
+ _update_features_from_html,
22
+ TwitterAPIError,
23
+ TwitterClient,
24
+ )
25
+
26
+
27
+ # ── _deep_get ────────────────────────────────────────────────────────────
28
+
29
+ class TestDeepGet:
30
+ def test_nested_dict(self):
31
+ data = {"a": {"b": {"c": 42}}}
32
+ assert _deep_get(data, "a", "b", "c") == 42
33
+
34
+ def test_missing_key(self):
35
+ assert _deep_get({"a": 1}, "b") is None
36
+
37
+ def test_deeply_missing(self):
38
+ assert _deep_get({"a": {"b": 1}}, "a", "c", "d") is None
39
+
40
+ def test_list_access(self):
41
+ data = {"items": [10, 20, 30]}
42
+ assert _deep_get(data, "items", 1) == 20
43
+
44
+ def test_list_out_of_bounds(self):
45
+ data = {"items": [10]}
46
+ assert _deep_get(data, "items", 5) is None
47
+
48
+ def test_none_input(self):
49
+ assert _deep_get(None, "a") is None
50
+
51
+ def test_empty_keys(self):
52
+ data = {"x": 1}
53
+ assert _deep_get(data) == data
54
+
55
+
56
+ # ── _parse_int ───────────────────────────────────────────────────────────
57
+
58
+ class TestParseInt:
59
+ def test_normal_int(self):
60
+ assert _parse_int(42, 0) == 42
61
+
62
+ def test_string_int(self):
63
+ assert _parse_int("123", 0) == 123
64
+
65
+ def test_float_string(self):
66
+ assert _parse_int("99.9", 0) == 99
67
+
68
+ def test_comma_separated(self):
69
+ assert _parse_int("1,234", 0) == 1234
70
+
71
+ def test_empty_string(self):
72
+ assert _parse_int("", 0) == 0
73
+
74
+ def test_none(self):
75
+ assert _parse_int(None, -1) == -1
76
+
77
+ def test_invalid(self):
78
+ assert _parse_int("abc", 5) == 5
79
+
80
+
81
+ # ── _extract_cursor ──────────────────────────────────────────────────────
82
+
83
+ class TestExtractCursor:
84
+ def test_bottom_cursor(self):
85
+ content = {"cursorType": "Bottom", "value": "cursor_abc"}
86
+ assert _extract_cursor(content) == "cursor_abc"
87
+
88
+ def test_top_cursor_ignored(self):
89
+ content = {"cursorType": "Top", "value": "cursor_top"}
90
+ assert _extract_cursor(content) is None
91
+
92
+ def test_no_cursor(self):
93
+ assert _extract_cursor({}) is None
94
+
95
+
96
+ # ── _extract_media ───────────────────────────────────────────────────────
97
+
98
+ class TestExtractMedia:
99
+ def test_photo(self):
100
+ legacy = {
101
+ "extended_entities": {
102
+ "media": [
103
+ {
104
+ "type": "photo",
105
+ "media_url_https": "https://pbs.twimg.com/img.jpg",
106
+ "original_info": {"width": 1200, "height": 800},
107
+ }
108
+ ]
109
+ }
110
+ }
111
+ media = _extract_media(legacy)
112
+ assert len(media) == 1
113
+ assert media[0].type == "photo"
114
+ assert media[0].url == "https://pbs.twimg.com/img.jpg"
115
+ assert media[0].width == 1200
116
+
117
+ def test_video_picks_highest_bitrate(self):
118
+ legacy = {
119
+ "extended_entities": {
120
+ "media": [
121
+ {
122
+ "type": "video",
123
+ "media_url_https": "https://pbs.twimg.com/thumb.jpg",
124
+ "original_info": {"width": 1920, "height": 1080},
125
+ "video_info": {
126
+ "variants": [
127
+ {"content_type": "video/mp4", "bitrate": 832000, "url": "https://low.mp4"},
128
+ {"content_type": "video/mp4", "bitrate": 2176000, "url": "https://high.mp4"},
129
+ {"content_type": "application/x-mpegURL", "url": "https://stream.m3u8"},
130
+ ]
131
+ },
132
+ }
133
+ ]
134
+ }
135
+ }
136
+ media = _extract_media(legacy)
137
+ assert len(media) == 1
138
+ assert media[0].type == "video"
139
+ assert media[0].url == "https://high.mp4"
140
+
141
+ def test_no_media(self):
142
+ assert _extract_media({}) == []
143
+
144
+ def test_animated_gif(self):
145
+ legacy = {
146
+ "extended_entities": {
147
+ "media": [
148
+ {
149
+ "type": "animated_gif",
150
+ "media_url_https": "https://pbs.twimg.com/gif.mp4",
151
+ "original_info": {"width": 480, "height": 270},
152
+ "video_info": {
153
+ "variants": [
154
+ {"content_type": "video/mp4", "bitrate": 0, "url": "https://gif.mp4"},
155
+ ]
156
+ },
157
+ }
158
+ ]
159
+ }
160
+ }
161
+ media = _extract_media(legacy)
162
+ assert len(media) == 1
163
+ assert media[0].type == "animated_gif"
164
+
165
+
166
+ # ── _build_graphql_url ───────────────────────────────────────────────────
167
+
168
+ class TestBuildGraphqlUrl:
169
+ def test_basic_url(self):
170
+ url = _build_graphql_url("abc123", "HomeTimeline", {"count": 20}, {"f1": True})
171
+ assert "graphql/abc123/HomeTimeline" in url
172
+ assert "variables=" in url
173
+ assert "features=" in url
174
+
175
+ def test_field_toggles(self):
176
+ url = _build_graphql_url("x", "Op", {}, {}, {"toggle": True})
177
+ assert "fieldToggles=" in url
178
+
179
+
180
+ # ── _best_chrome_target ──────────────────────────────────────────────────
181
+
182
+ class TestBestChromeTarget:
183
+ def test_returns_string(self):
184
+ target = _best_chrome_target()
185
+ assert isinstance(target, str)
186
+ assert "chrome" in target
187
+
188
+ def test_fallback_when_no_browser_type(self):
189
+ with patch.dict("sys.modules", {"curl_cffi.requests": MagicMock(BrowserType=MagicMock(side_effect=TypeError))}):
190
+ # Force re-evaluation by clearing cached result
191
+ # When BrowserType iteration fails, should still return a fallback
192
+ target = _best_chrome_target()
193
+ assert isinstance(target, str)
194
+
195
+
196
+ # ── _update_features_from_html ───────────────────────────────────────────
197
+
198
+ class TestUpdateFeaturesFromHtml:
199
+ def test_extracts_feature_flags(self):
200
+ # Save original state
201
+ original = dict(FEATURES)
202
+ try:
203
+ html = '''
204
+ "responsive_web_test_feature":{"value":true},
205
+ "responsive_web_another_feature":{"value":false},
206
+ "rweb_some_flag":{"value":true}
207
+ '''
208
+ _update_features_from_html(html)
209
+ assert FEATURES["responsive_web_test_feature"] is True
210
+ assert FEATURES["responsive_web_another_feature"] is False
211
+ assert FEATURES["rweb_some_flag"] is True
212
+ finally:
213
+ # Restore original state
214
+ FEATURES.clear()
215
+ FEATURES.update(original)
216
+
217
+ def test_ignores_non_feature_keys(self):
218
+ original = dict(FEATURES)
219
+ try:
220
+ html = '"some_random_key":{"value":true}'
221
+ _update_features_from_html(html)
222
+ assert "some_random_key" not in FEATURES
223
+ finally:
224
+ FEATURES.clear()
225
+ FEATURES.update(original)
226
+
227
+ def test_handles_empty_html(self):
228
+ _update_features_from_html("")
229
+
230
+ def test_handles_malformed_html(self):
231
+ _update_features_from_html("not json at all {{{")
232
+
233
+
234
+ # ── TwitterClient._build_headers ─────────────────────────────────────────
235
+
236
+ class TestBuildHeaders:
237
+ @patch("twitter_cli.client._get_cffi_session")
238
+ @patch("twitter_cli.client._gen_ct_headers", return_value={})
239
+ def test_required_headers_present(self, mock_ct_headers, mock_session):
240
+ mock_session.return_value = MagicMock()
241
+ mock_session.return_value.get = MagicMock(side_effect=Exception("skip init"))
242
+
243
+ client = TwitterClient.__new__(TwitterClient)
244
+ client._auth_token = "test_token"
245
+ client._ct0 = "test_ct0"
246
+ client._cookie_string = None
247
+ client._request_delay = 2.5
248
+ client._max_retries = 3
249
+ client._retry_base_delay = 5.0
250
+ client._max_count = 200
251
+ client._client_transaction = None
252
+ client._ct_init_attempted = True
253
+
254
+ headers = client._build_headers("https://x.com/i/api/graphql/test", "GET")
255
+
256
+ assert "Authorization" in headers
257
+ assert "Bearer" in headers["Authorization"]
258
+ assert headers["X-Csrf-Token"] == "test_ct0"
259
+ assert headers["X-Twitter-Auth-Type"] == "OAuth2Session"
260
+ assert "User-Agent" in headers
261
+ assert "sec-ch-ua" in headers
262
+
263
+ @patch("twitter_cli.client._get_cffi_session")
264
+ @patch("twitter_cli.client._gen_ct_headers", return_value={})
265
+ def test_cookie_string_used_when_available(self, mock_ct_headers, mock_session):
266
+ mock_session.return_value = MagicMock()
267
+ mock_session.return_value.get = MagicMock(side_effect=Exception("skip"))
268
+
269
+ client = TwitterClient.__new__(TwitterClient)
270
+ client._auth_token = "token"
271
+ client._ct0 = "ct0"
272
+ client._cookie_string = "auth_token=x; ct0=y; other=z"
273
+ client._request_delay = 2.5
274
+ client._max_retries = 3
275
+ client._retry_base_delay = 5.0
276
+ client._max_count = 200
277
+ client._client_transaction = None
278
+ client._ct_init_attempted = True
279
+
280
+ headers = client._build_headers()
281
+ assert headers["Cookie"] == "auth_token=x; ct0=y; other=z"
282
+
283
+
284
+ # ── TwitterClient._parse_tweet_result ─────────────────────────────────────
285
+
286
+ class TestParseTweetResult:
287
+ SAMPLE_TWEET_RESULT = {
288
+ "__typename": "Tweet",
289
+ "rest_id": "1234567890",
290
+ "core": {
291
+ "user_results": {
292
+ "result": {
293
+ "rest_id": "user123",
294
+ "core": {"name": "Test User", "screen_name": "testuser"},
295
+ "legacy": {
296
+ "name": "Test User",
297
+ "screen_name": "testuser",
298
+ "verified": False,
299
+ "profile_image_url_https": "https://img.com/avatar.jpg",
300
+ },
301
+ "is_blue_verified": True,
302
+ }
303
+ }
304
+ },
305
+ "legacy": {
306
+ "full_text": "Hello world! This is a test tweet.",
307
+ "created_at": "Sat Mar 08 12:00:00 +0000 2026",
308
+ "favorite_count": 100,
309
+ "retweet_count": 25,
310
+ "reply_count": 5,
311
+ "quote_count": 3,
312
+ "bookmark_count": 10,
313
+ "lang": "en",
314
+ "entities": {"urls": []},
315
+ },
316
+ "views": {"count": "5000"},
317
+ }
318
+
319
+ @patch("twitter_cli.client._get_cffi_session")
320
+ @patch("twitter_cli.client._gen_ct_headers", return_value={})
321
+ def test_parses_basic_tweet(self, mock_ct_headers, mock_session):
322
+ mock_session.return_value = MagicMock()
323
+ mock_session.return_value.get = MagicMock(side_effect=Exception("skip"))
324
+
325
+ client = TwitterClient.__new__(TwitterClient)
326
+ client._ct_init_attempted = True
327
+ client._client_transaction = None
328
+
329
+ tweet = client._parse_tweet_result(copy.deepcopy(self.SAMPLE_TWEET_RESULT))
330
+ assert tweet is not None
331
+ assert tweet.id == "1234567890"
332
+ assert tweet.text == "Hello world! This is a test tweet."
333
+ assert tweet.author.screen_name == "testuser"
334
+ assert tweet.author.verified is True # is_blue_verified
335
+ assert tweet.metrics.likes == 100
336
+ assert tweet.metrics.views == 5000
337
+ assert tweet.lang == "en"
338
+ assert tweet.is_retweet is False
339
+
340
+ @patch("twitter_cli.client._get_cffi_session")
341
+ @patch("twitter_cli.client._gen_ct_headers", return_value={})
342
+ def test_parses_tombstone_returns_none(self, mock_ct_headers, mock_session):
343
+ mock_session.return_value = MagicMock()
344
+ mock_session.return_value.get = MagicMock(side_effect=Exception("skip"))
345
+
346
+ client = TwitterClient.__new__(TwitterClient)
347
+ client._ct_init_attempted = True
348
+ client._client_transaction = None
349
+
350
+ result = {"__typename": "TweetTombstone"}
351
+ assert client._parse_tweet_result(result) is None
352
+
353
+ @patch("twitter_cli.client._get_cffi_session")
354
+ @patch("twitter_cli.client._gen_ct_headers", return_value={})
355
+ def test_parses_visibility_wrapper(self, mock_ct_headers, mock_session):
356
+ mock_session.return_value = MagicMock()
357
+ mock_session.return_value.get = MagicMock(side_effect=Exception("skip"))
358
+
359
+ client = TwitterClient.__new__(TwitterClient)
360
+ client._ct_init_attempted = True
361
+ client._client_transaction = None
362
+
363
+ wrapped = {
364
+ "__typename": "TweetWithVisibilityResults",
365
+ "tweet": copy.deepcopy(self.SAMPLE_TWEET_RESULT),
366
+ }
367
+ tweet = client._parse_tweet_result(wrapped)
368
+ assert tweet is not None
369
+ assert tweet.id == "1234567890"
370
+
371
+ @patch("twitter_cli.client._get_cffi_session")
372
+ @patch("twitter_cli.client._gen_ct_headers", return_value={})
373
+ def test_depth_limit(self, mock_ct_headers, mock_session):
374
+ mock_session.return_value = MagicMock()
375
+ mock_session.return_value.get = MagicMock(side_effect=Exception("skip"))
376
+
377
+ client = TwitterClient.__new__(TwitterClient)
378
+ client._ct_init_attempted = True
379
+ client._client_transaction = None
380
+
381
+ assert client._parse_tweet_result(self.SAMPLE_TWEET_RESULT, depth=3) is None
382
+
383
+
384
+ # ── TwitterAPIError ──────────────────────────────────────────────────────
385
+
386
+ class TestTwitterAPIError:
387
+ def test_stores_status_code(self):
388
+ err = TwitterAPIError(429, "Rate limited")
389
+ assert err.status_code == 429
390
+ assert str(err) == "Rate limited"
391
+
392
+ def test_is_runtime_error(self):
393
+ err = TwitterAPIError(500, "Server error")
394
+ assert isinstance(err, RuntimeError)
@@ -2,8 +2,10 @@
2
2
 
3
3
  Supports:
4
4
  1. Environment variables: TWITTER_AUTH_TOKEN + TWITTER_CT0
5
- 2. Auto-extract from browser via browser-cookie3 (subprocess)
5
+ 2. Auto-extract from browser via browser-cookie3
6
6
  Extracts ALL Twitter cookies for full browser-like fingerprint.
7
+ Prefers in-process extraction (required on macOS for Keychain access),
8
+ falls back to subprocess if in-process fails (e.g. SQLite lock).
7
9
  """
8
10
 
9
11
  from __future__ import annotations
@@ -21,6 +23,14 @@ from .constants import BEARER_TOKEN, USER_AGENT
21
23
 
22
24
  logger = logging.getLogger(__name__)
23
25
 
26
+ # Domains to match for Twitter cookies
27
+ _TWITTER_DOMAINS = {"x.com", "twitter.com", ".x.com", ".twitter.com"}
28
+
29
+
30
+ def _is_twitter_domain(domain):
31
+ # type: (str) -> bool
32
+ return domain in _TWITTER_DOMAINS or domain.endswith(".x.com") or domain.endswith(".twitter.com")
33
+
24
34
 
25
35
  def load_from_env() -> Optional[Dict[str, str]]:
26
36
  """Load cookies from environment variables."""
@@ -39,6 +49,8 @@ def verify_cookies(auth_token, ct0, cookie_string=None):
39
49
  Tries multiple endpoints. Only raises on clear auth failures (401/403).
40
50
  For other errors (404, network), returns empty dict (proceed without verification).
41
51
  """
52
+ from .client import _best_chrome_target
53
+
42
54
  urls = [
43
55
  "https://api.x.com/1.1/account/verify_credentials.json",
44
56
  "https://x.com/i/api/1.1/account/settings.json",
@@ -58,7 +70,7 @@ def verify_cookies(auth_token, ct0, cookie_string=None):
58
70
 
59
71
  proxy = os.environ.get("TWITTER_PROXY", "")
60
72
  session = _cffi_requests.Session(
61
- impersonate="chrome133",
73
+ impersonate=_best_chrome_target(),
62
74
  proxies={"https": proxy, "http": proxy} if proxy else None,
63
75
  )
64
76
 
@@ -85,16 +97,66 @@ def verify_cookies(auth_token, ct0, cookie_string=None):
85
97
  return {}
86
98
 
87
99
 
88
- def extract_from_browser() -> Optional[Dict[str, str]]:
89
- """Auto-extract ALL Twitter cookies from local browser using browser-cookie3.
100
+ def _extract_cookies_from_jar(jar):
101
+ # type: (Any) -> Optional[Dict[str, str]]
102
+ """Extract Twitter cookies from a cookie jar."""
103
+ result = {} # type: Dict[str, str]
104
+ all_cookies = {} # type: Dict[str, str]
105
+ for cookie in jar:
106
+ domain = cookie.domain or ""
107
+ if _is_twitter_domain(domain):
108
+ if cookie.name == "auth_token":
109
+ result["auth_token"] = cookie.value
110
+ elif cookie.name == "ct0":
111
+ result["ct0"] = cookie.value
112
+ if cookie.name and cookie.value:
113
+ all_cookies[cookie.name] = cookie.value
114
+ if "auth_token" in result and "ct0" in result:
115
+ cookies = {"auth_token": result["auth_token"], "ct0": result["ct0"]}
116
+ if all_cookies:
117
+ cookies["cookie_string"] = "; ".join("%s=%s" % (k, v) for k, v in all_cookies.items())
118
+ logger.info("Extracted %d total cookies for full browser fingerprint", len(all_cookies))
119
+ return cookies
120
+ return None
90
121
 
91
- Extracts every cookie for .x.com and .twitter.com domains, not just
92
- auth_token and ct0. This makes requests indistinguishable from real
93
- browser traffic at the cookie level.
94
122
 
95
- Tries browsers in order: Chrome -> Edge -> Firefox -> Brave.
96
- Runs in a subprocess to avoid SQLite database lock issues.
123
+ def _extract_in_process():
124
+ # type: () -> Optional[Dict[str, str]]
125
+ """Extract cookies in the main process (required on macOS for Keychain access).
126
+
127
+ On macOS, Chrome encrypts cookies using a key stored in the system Keychain.
128
+ Child processes do NOT inherit the parent's Keychain authorization, so
129
+ browser_cookie3 must run in the main process to decrypt cookies.
97
130
  """
131
+ try:
132
+ import browser_cookie3
133
+ except ImportError:
134
+ logger.debug("browser_cookie3 not installed, skipping in-process extraction")
135
+ return None
136
+
137
+ browsers = [
138
+ ("chrome", browser_cookie3.chrome),
139
+ ("edge", browser_cookie3.edge),
140
+ ("firefox", browser_cookie3.firefox),
141
+ ("brave", browser_cookie3.brave),
142
+ ]
143
+
144
+ for name, fn in browsers:
145
+ try:
146
+ jar = fn()
147
+ except Exception as e:
148
+ logger.debug("%s in-process extraction failed: %s", name, e)
149
+ continue
150
+ cookies = _extract_cookies_from_jar(jar)
151
+ if cookies:
152
+ logger.info("Found cookies in %s (in-process)", name)
153
+ return cookies
154
+ return None
155
+
156
+
157
+ def _extract_via_subprocess():
158
+ # type: () -> Optional[Dict[str, str]]
159
+ """Extract cookies via subprocess (fallback if in-process fails, e.g. SQLite lock)."""
98
160
  extract_script = '''
99
161
  import json, sys
100
162
  try:
@@ -124,7 +186,6 @@ for name, fn in browsers:
124
186
  result["auth_token"] = cookie.value
125
187
  elif cookie.name == "ct0":
126
188
  result["ct0"] = cookie.value
127
- # Collect ALL cookies for full browser fingerprint
128
189
  if cookie.name and cookie.value:
129
190
  all_cookies[cookie.name] = cookie.value
130
191
  if "auth_token" in result and "ct0" in result:
@@ -164,7 +225,7 @@ sys.exit(1)
164
225
  data = json.loads(output)
165
226
  if "error" in data:
166
227
  return None
167
- logger.info("Found cookies in %s", data.get("browser", "unknown"))
228
+ logger.info("Found cookies in %s (subprocess)", data.get("browser", "unknown"))
168
229
 
169
230
  # Build full cookie string from all extracted cookies
170
231
  cookies = {"auth_token": data["auth_token"], "ct0": data["ct0"]}
@@ -178,6 +239,23 @@ sys.exit(1)
178
239
  return None
179
240
 
180
241
 
242
+ def extract_from_browser() -> Optional[Dict[str, str]]:
243
+ """Auto-extract ALL Twitter cookies from local browser using browser-cookie3.
244
+
245
+ Strategy:
246
+ 1. Try in-process first (required on macOS for Keychain access)
247
+ 2. Fall back to subprocess (handles SQLite lock when browser is running)
248
+ """
249
+ # 1. In-process (works on macOS, may fail with SQLite lock)
250
+ cookies = _extract_in_process()
251
+ if cookies:
252
+ return cookies
253
+
254
+ # 2. Subprocess fallback (handles SQLite lock, but fails on macOS Keychain)
255
+ logger.debug("In-process extraction failed, trying subprocess fallback")
256
+ return _extract_via_subprocess()
257
+
258
+
181
259
  def get_cookies() -> Dict[str, str]:
182
260
  """Get Twitter cookies. Priority: env vars -> browser extraction (Chrome/Edge/Firefox/Brave).
183
261
 
@@ -205,3 +283,4 @@ def get_cookies() -> Dict[str, str]:
205
283
  verify_cookies(cookies["auth_token"], cookies["ct0"], cookies.get("cookie_string"))
206
284
  return cookies
207
285
 
286
+
@@ -53,7 +53,7 @@ TWITTER_OPENAPI_URL = (
53
53
  "main/src/config/placeholder.json"
54
54
  )
55
55
 
56
- FEATURES = {
56
+ _DEFAULT_FEATURES = {
57
57
  "rweb_video_screen_enabled": False,
58
58
  "profile_label_improvements_pcf_label_in_post_enabled": True,
59
59
  "responsive_web_profile_redirect_enabled": False,
@@ -93,6 +93,9 @@ FEATURES = {
93
93
  "responsive_web_enhance_cards_enabled": False,
94
94
  }
95
95
 
96
+ # Features dict that gets updated dynamically from x.com JS bundles
97
+ FEATURES = dict(_DEFAULT_FEATURES)
98
+
96
99
  # Module-level caches (not thread-safe — CLI is single-threaded)
97
100
  _cached_query_ids = {} # type: Dict[str, str]
98
101
  _bundles_scanned = False
@@ -106,6 +109,31 @@ class TwitterAPIError(RuntimeError):
106
109
  super().__init__(message)
107
110
  self.status_code = status_code
108
111
 
112
+ def _best_chrome_target():
113
+ # type: () -> str
114
+ """Detect the best available Chrome impersonation target at runtime.
115
+
116
+ curl_cffi versions differ in which Chrome targets they ship.
117
+ e.g. 0.14.0 has chrome133a but not chrome133.
118
+ """
119
+ try:
120
+ from curl_cffi.requests import BrowserType
121
+ available = {e.value for e in BrowserType}
122
+ except Exception:
123
+ available = set()
124
+
125
+ # Preference order: exact chrome versions, then suffixed variants
126
+ for target in ("chrome133", "chrome133a", "chrome136", "chrome131", "chrome130"):
127
+ if target in available:
128
+ return target
129
+ # Fallback: pick highest chrome* with a pure numeric suffix
130
+ chrome_targets = sorted(
131
+ [v for v in available if v.startswith("chrome") and v.replace("chrome", "").isdigit()],
132
+ key=lambda x: int(x.replace("chrome", "")),
133
+ reverse=True,
134
+ )
135
+ return chrome_targets[0] if chrome_targets else "chrome131"
136
+
109
137
 
110
138
  def _get_cffi_session():
111
139
  # type: () -> Any
@@ -114,10 +142,12 @@ def _get_cffi_session():
114
142
  if _cffi_session is None:
115
143
  import os
116
144
  proxy = os.environ.get("TWITTER_PROXY", "")
145
+ target = _best_chrome_target()
117
146
  _cffi_session = _cffi_requests.Session(
118
- impersonate="chrome133",
147
+ impersonate=target,
119
148
  proxies={"https": proxy, "http": proxy} if proxy else None,
120
149
  )
150
+ logger.info("curl_cffi impersonating %s", target)
121
151
  if proxy:
122
152
  logger.info("Using proxy: %s", proxy[:20] + "...")
123
153
  return _cffi_session
@@ -184,6 +214,35 @@ def _scan_bundles():
184
214
  logger.info("Scanned %d JS bundles, cached %d query IDs", len(script_urls), len(_cached_query_ids))
185
215
 
186
216
 
217
+ def _update_features_from_html(html):
218
+ # type: (str) -> None
219
+ """Extract live feature flags from x.com HTML and update the global FEATURES dict.
220
+
221
+ Twitter embeds feature switch config in inline scripts on the homepage.
222
+ We parse these to keep FEATURES in sync with the current frontend.
223
+ """
224
+ try:
225
+ # Look for feature flags in inline script content
226
+ # Pattern: "featureSwitch":{"...":{"value":true/false},...}
227
+ # Also try: features:{key:!0, key2:!1, ...} in JS bundles
228
+ feature_pattern = re.compile(
229
+ r'"([a-z][a-z0-9_]+)":\s*\{\s*"value"\s*:\s*(true|false)',
230
+ re.IGNORECASE,
231
+ )
232
+ found = 0
233
+ for match in feature_pattern.finditer(html):
234
+ key = match.group(1)
235
+ value = match.group(2).lower() == "true"
236
+ # Only update keys that look like feature flags
237
+ if any(prefix in key for prefix in ("responsive_web_", "rweb_", "longform_", "creator_", "communities_", "c9s_")):
238
+ FEATURES[key] = value
239
+ found += 1
240
+ if found:
241
+ logger.info("Updated %d feature flags from x.com", found)
242
+ except Exception as exc:
243
+ logger.debug("Feature extraction from HTML failed: %s", exc)
244
+
245
+
187
246
  def _fetch_from_github(operation_name):
188
247
  # type: (str) -> Optional[str]
189
248
  """Fetch queryId from community-maintained twitter-openapi file."""
@@ -441,6 +500,13 @@ class TwitterClient:
441
500
 
442
501
  # ── Write operations ────────────────────────────────────────────────
443
502
 
503
+ def _write_delay(self):
504
+ # type: () -> None
505
+ """Sleep a random interval after write operations to avoid rate limits."""
506
+ delay = random.uniform(1.5, 4.0)
507
+ logger.debug("Write operation delay: %.1fs", delay)
508
+ time.sleep(delay)
509
+
444
510
  def create_tweet(self, text, reply_to_id=None):
445
511
  # type: (str, Optional[str]) -> str
446
512
  """Post a new tweet. Returns the new tweet ID."""
@@ -456,6 +522,7 @@ class TwitterClient:
456
522
  "exclude_reply_user_ids": [],
457
523
  }
458
524
  data = self._graphql_post("CreateTweet", variables, FEATURES)
525
+ self._write_delay()
459
526
  result = _deep_get(data, "data", "create_tweet", "tweet_results", "result")
460
527
  if result:
461
528
  return result.get("rest_id", "")
@@ -466,42 +533,49 @@ class TwitterClient:
466
533
  """Delete a tweet. Returns True on success."""
467
534
  variables = {"tweet_id": tweet_id, "dark_request": False}
468
535
  self._graphql_post("DeleteTweet", variables)
536
+ self._write_delay()
469
537
  return True
470
538
 
471
539
  def like_tweet(self, tweet_id):
472
540
  # type: (str) -> bool
473
541
  """Like a tweet. Returns True on success."""
474
542
  self._graphql_post("FavoriteTweet", {"tweet_id": tweet_id})
543
+ self._write_delay()
475
544
  return True
476
545
 
477
546
  def unlike_tweet(self, tweet_id):
478
547
  # type: (str) -> bool
479
548
  """Unlike a tweet. Returns True on success."""
480
549
  self._graphql_post("UnfavoriteTweet", {"tweet_id": tweet_id, "dark_request": False})
550
+ self._write_delay()
481
551
  return True
482
552
 
483
553
  def retweet(self, tweet_id):
484
554
  # type: (str) -> bool
485
555
  """Retweet a tweet. Returns True on success."""
486
556
  self._graphql_post("CreateRetweet", {"tweet_id": tweet_id, "dark_request": False})
557
+ self._write_delay()
487
558
  return True
488
559
 
489
560
  def unretweet(self, tweet_id):
490
561
  # type: (str) -> bool
491
562
  """Undo a retweet. Returns True on success."""
492
563
  self._graphql_post("DeleteRetweet", {"source_tweet_id": tweet_id, "dark_request": False})
564
+ self._write_delay()
493
565
  return True
494
566
 
495
567
  def bookmark_tweet(self, tweet_id):
496
568
  # type: (str) -> bool
497
569
  """Bookmark a tweet. Returns True on success."""
498
570
  self._graphql_post("CreateBookmark", {"tweet_id": tweet_id})
571
+ self._write_delay()
499
572
  return True
500
573
 
501
574
  def unbookmark_tweet(self, tweet_id):
502
575
  # type: (str) -> bool
503
576
  """Remove a tweet from bookmarks. Returns True on success."""
504
577
  self._graphql_post("DeleteBookmark", {"tweet_id": tweet_id})
578
+ self._write_delay()
505
579
  return True
506
580
 
507
581
  def _fetch_timeline(self, operation_name, count, get_instructions, extra_variables=None, override_base_variables=False, field_toggles=None):
@@ -582,7 +656,10 @@ class TwitterClient:
582
656
 
583
657
  def _ensure_client_transaction(self):
584
658
  # type: () -> None
585
- """Initialize ClientTransaction for x-client-transaction-id header."""
659
+ """Initialize ClientTransaction for x-client-transaction-id header.
660
+
661
+ Also attempts to extract live feature flags from JS bundles.
662
+ """
586
663
  if self._ct_init_attempted:
587
664
  return
588
665
  self._ct_init_attempted = True
@@ -605,6 +682,9 @@ class TwitterClient:
605
682
  ondemand_file_response=ondemand_file.text,
606
683
  )
607
684
  logger.info("ClientTransaction initialized for x-client-transaction-id")
685
+
686
+ # Try to extract live FEATURES from the homepage JS bundles
687
+ _update_features_from_html(home_page.text)
608
688
  except Exception as exc:
609
689
  logger.warning("Failed to init ClientTransaction: %s", exc)
610
690
 
@@ -950,7 +950,7 @@ wheels = [
950
950
 
951
951
  [[package]]
952
952
  name = "twitter-cli"
953
- version = "0.3.3"
953
+ version = "0.4.0"
954
954
  source = { editable = "." }
955
955
  dependencies = [
956
956
  { name = "beautifulsoup4" },
File without changes
File without changes
File without changes
File without changes