twitter-cli 0.4.0__tar.gz → 0.4.2__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.
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/PKG-INFO +3 -3
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/README.md +2 -2
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/pyproject.toml +1 -1
- twitter_cli-0.4.2/tests/test_client.py +411 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/twitter_cli/client.py +63 -4
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/uv.lock +1 -1
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/.github/workflows/ci.yml +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/.github/workflows/publish-clawhub.yml +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/.github/workflows/publish.yml +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/.gitignore +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/LICENSE +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/SKILL.md +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/config.yaml +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/tests/conftest.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/tests/test_cli.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/tests/test_config.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/tests/test_config_normalization.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/tests/test_filter.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/tests/test_serialization.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/twitter_cli/__init__.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/twitter_cli/auth.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/twitter_cli/cli.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/twitter_cli/config.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/twitter_cli/constants.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/twitter_cli/filter.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/twitter_cli/formatter.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/twitter_cli/models.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.2}/twitter_cli/serialization.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: twitter-cli
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.2
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
364
|
+
使用代理可以降低 IP 维度的风控风险。
|
|
365
365
|
|
|
366
366
|
### 筛选算法
|
|
367
367
|
|
|
@@ -0,0 +1,411 @@
|
|
|
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
|
+
def test_false_features_omitted_from_url(self):
|
|
180
|
+
"""False-valued features should be omitted to keep URL short (avoid 414)."""
|
|
181
|
+
features = {"enabled_flag": True, "disabled_flag": False, "another_enabled": True}
|
|
182
|
+
url = _build_graphql_url("q", "Op", {}, features)
|
|
183
|
+
assert "enabled_flag" in url
|
|
184
|
+
assert "another_enabled" in url
|
|
185
|
+
assert "disabled_flag" not in url
|
|
186
|
+
|
|
187
|
+
def test_url_length_with_full_features(self):
|
|
188
|
+
"""URL with full FEATURES dict should stay under 8000 chars (server limit)."""
|
|
189
|
+
url = _build_graphql_url(
|
|
190
|
+
"abc123", "SearchTimeline",
|
|
191
|
+
{"rawQuery": "AI agent", "querySource": "typed_query", "product": "Latest", "count": 50},
|
|
192
|
+
FEATURES,
|
|
193
|
+
)
|
|
194
|
+
assert len(url) < 8000, f"URL too long: {len(url)} chars"
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
# ── _best_chrome_target ──────────────────────────────────────────────────
|
|
198
|
+
|
|
199
|
+
class TestBestChromeTarget:
|
|
200
|
+
def test_returns_string(self):
|
|
201
|
+
target = _best_chrome_target()
|
|
202
|
+
assert isinstance(target, str)
|
|
203
|
+
assert "chrome" in target
|
|
204
|
+
|
|
205
|
+
def test_fallback_when_no_browser_type(self):
|
|
206
|
+
with patch.dict("sys.modules", {"curl_cffi.requests": MagicMock(BrowserType=MagicMock(side_effect=TypeError))}):
|
|
207
|
+
# Force re-evaluation by clearing cached result
|
|
208
|
+
# When BrowserType iteration fails, should still return a fallback
|
|
209
|
+
target = _best_chrome_target()
|
|
210
|
+
assert isinstance(target, str)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
# ── _update_features_from_html ───────────────────────────────────────────
|
|
214
|
+
|
|
215
|
+
class TestUpdateFeaturesFromHtml:
|
|
216
|
+
def test_extracts_feature_flags(self):
|
|
217
|
+
# Save original state
|
|
218
|
+
original = dict(FEATURES)
|
|
219
|
+
try:
|
|
220
|
+
html = '''
|
|
221
|
+
"responsive_web_test_feature":{"value":true},
|
|
222
|
+
"responsive_web_another_feature":{"value":false},
|
|
223
|
+
"rweb_some_flag":{"value":true}
|
|
224
|
+
'''
|
|
225
|
+
_update_features_from_html(html)
|
|
226
|
+
assert FEATURES["responsive_web_test_feature"] is True
|
|
227
|
+
assert FEATURES["responsive_web_another_feature"] is False
|
|
228
|
+
assert FEATURES["rweb_some_flag"] is True
|
|
229
|
+
finally:
|
|
230
|
+
# Restore original state
|
|
231
|
+
FEATURES.clear()
|
|
232
|
+
FEATURES.update(original)
|
|
233
|
+
|
|
234
|
+
def test_ignores_non_feature_keys(self):
|
|
235
|
+
original = dict(FEATURES)
|
|
236
|
+
try:
|
|
237
|
+
html = '"some_random_key":{"value":true}'
|
|
238
|
+
_update_features_from_html(html)
|
|
239
|
+
assert "some_random_key" not in FEATURES
|
|
240
|
+
finally:
|
|
241
|
+
FEATURES.clear()
|
|
242
|
+
FEATURES.update(original)
|
|
243
|
+
|
|
244
|
+
def test_handles_empty_html(self):
|
|
245
|
+
_update_features_from_html("")
|
|
246
|
+
|
|
247
|
+
def test_handles_malformed_html(self):
|
|
248
|
+
_update_features_from_html("not json at all {{{")
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
# ── TwitterClient._build_headers ─────────────────────────────────────────
|
|
252
|
+
|
|
253
|
+
class TestBuildHeaders:
|
|
254
|
+
@patch("twitter_cli.client._get_cffi_session")
|
|
255
|
+
@patch("twitter_cli.client._gen_ct_headers", return_value={})
|
|
256
|
+
def test_required_headers_present(self, mock_ct_headers, mock_session):
|
|
257
|
+
mock_session.return_value = MagicMock()
|
|
258
|
+
mock_session.return_value.get = MagicMock(side_effect=Exception("skip init"))
|
|
259
|
+
|
|
260
|
+
client = TwitterClient.__new__(TwitterClient)
|
|
261
|
+
client._auth_token = "test_token"
|
|
262
|
+
client._ct0 = "test_ct0"
|
|
263
|
+
client._cookie_string = None
|
|
264
|
+
client._request_delay = 2.5
|
|
265
|
+
client._max_retries = 3
|
|
266
|
+
client._retry_base_delay = 5.0
|
|
267
|
+
client._max_count = 200
|
|
268
|
+
client._client_transaction = None
|
|
269
|
+
client._ct_init_attempted = True
|
|
270
|
+
|
|
271
|
+
headers = client._build_headers("https://x.com/i/api/graphql/test", "GET")
|
|
272
|
+
|
|
273
|
+
assert "Authorization" in headers
|
|
274
|
+
assert "Bearer" in headers["Authorization"]
|
|
275
|
+
assert headers["X-Csrf-Token"] == "test_ct0"
|
|
276
|
+
assert headers["X-Twitter-Auth-Type"] == "OAuth2Session"
|
|
277
|
+
assert "User-Agent" in headers
|
|
278
|
+
assert "sec-ch-ua" in headers
|
|
279
|
+
|
|
280
|
+
@patch("twitter_cli.client._get_cffi_session")
|
|
281
|
+
@patch("twitter_cli.client._gen_ct_headers", return_value={})
|
|
282
|
+
def test_cookie_string_used_when_available(self, mock_ct_headers, mock_session):
|
|
283
|
+
mock_session.return_value = MagicMock()
|
|
284
|
+
mock_session.return_value.get = MagicMock(side_effect=Exception("skip"))
|
|
285
|
+
|
|
286
|
+
client = TwitterClient.__new__(TwitterClient)
|
|
287
|
+
client._auth_token = "token"
|
|
288
|
+
client._ct0 = "ct0"
|
|
289
|
+
client._cookie_string = "auth_token=x; ct0=y; other=z"
|
|
290
|
+
client._request_delay = 2.5
|
|
291
|
+
client._max_retries = 3
|
|
292
|
+
client._retry_base_delay = 5.0
|
|
293
|
+
client._max_count = 200
|
|
294
|
+
client._client_transaction = None
|
|
295
|
+
client._ct_init_attempted = True
|
|
296
|
+
|
|
297
|
+
headers = client._build_headers()
|
|
298
|
+
assert headers["Cookie"] == "auth_token=x; ct0=y; other=z"
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
# ── TwitterClient._parse_tweet_result ─────────────────────────────────────
|
|
302
|
+
|
|
303
|
+
class TestParseTweetResult:
|
|
304
|
+
SAMPLE_TWEET_RESULT = {
|
|
305
|
+
"__typename": "Tweet",
|
|
306
|
+
"rest_id": "1234567890",
|
|
307
|
+
"core": {
|
|
308
|
+
"user_results": {
|
|
309
|
+
"result": {
|
|
310
|
+
"rest_id": "user123",
|
|
311
|
+
"core": {"name": "Test User", "screen_name": "testuser"},
|
|
312
|
+
"legacy": {
|
|
313
|
+
"name": "Test User",
|
|
314
|
+
"screen_name": "testuser",
|
|
315
|
+
"verified": False,
|
|
316
|
+
"profile_image_url_https": "https://img.com/avatar.jpg",
|
|
317
|
+
},
|
|
318
|
+
"is_blue_verified": True,
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
},
|
|
322
|
+
"legacy": {
|
|
323
|
+
"full_text": "Hello world! This is a test tweet.",
|
|
324
|
+
"created_at": "Sat Mar 08 12:00:00 +0000 2026",
|
|
325
|
+
"favorite_count": 100,
|
|
326
|
+
"retweet_count": 25,
|
|
327
|
+
"reply_count": 5,
|
|
328
|
+
"quote_count": 3,
|
|
329
|
+
"bookmark_count": 10,
|
|
330
|
+
"lang": "en",
|
|
331
|
+
"entities": {"urls": []},
|
|
332
|
+
},
|
|
333
|
+
"views": {"count": "5000"},
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
@patch("twitter_cli.client._get_cffi_session")
|
|
337
|
+
@patch("twitter_cli.client._gen_ct_headers", return_value={})
|
|
338
|
+
def test_parses_basic_tweet(self, mock_ct_headers, mock_session):
|
|
339
|
+
mock_session.return_value = MagicMock()
|
|
340
|
+
mock_session.return_value.get = MagicMock(side_effect=Exception("skip"))
|
|
341
|
+
|
|
342
|
+
client = TwitterClient.__new__(TwitterClient)
|
|
343
|
+
client._ct_init_attempted = True
|
|
344
|
+
client._client_transaction = None
|
|
345
|
+
|
|
346
|
+
tweet = client._parse_tweet_result(copy.deepcopy(self.SAMPLE_TWEET_RESULT))
|
|
347
|
+
assert tweet is not None
|
|
348
|
+
assert tweet.id == "1234567890"
|
|
349
|
+
assert tweet.text == "Hello world! This is a test tweet."
|
|
350
|
+
assert tweet.author.screen_name == "testuser"
|
|
351
|
+
assert tweet.author.verified is True # is_blue_verified
|
|
352
|
+
assert tweet.metrics.likes == 100
|
|
353
|
+
assert tweet.metrics.views == 5000
|
|
354
|
+
assert tweet.lang == "en"
|
|
355
|
+
assert tweet.is_retweet is False
|
|
356
|
+
|
|
357
|
+
@patch("twitter_cli.client._get_cffi_session")
|
|
358
|
+
@patch("twitter_cli.client._gen_ct_headers", return_value={})
|
|
359
|
+
def test_parses_tombstone_returns_none(self, mock_ct_headers, mock_session):
|
|
360
|
+
mock_session.return_value = MagicMock()
|
|
361
|
+
mock_session.return_value.get = MagicMock(side_effect=Exception("skip"))
|
|
362
|
+
|
|
363
|
+
client = TwitterClient.__new__(TwitterClient)
|
|
364
|
+
client._ct_init_attempted = True
|
|
365
|
+
client._client_transaction = None
|
|
366
|
+
|
|
367
|
+
result = {"__typename": "TweetTombstone"}
|
|
368
|
+
assert client._parse_tweet_result(result) is None
|
|
369
|
+
|
|
370
|
+
@patch("twitter_cli.client._get_cffi_session")
|
|
371
|
+
@patch("twitter_cli.client._gen_ct_headers", return_value={})
|
|
372
|
+
def test_parses_visibility_wrapper(self, mock_ct_headers, mock_session):
|
|
373
|
+
mock_session.return_value = MagicMock()
|
|
374
|
+
mock_session.return_value.get = MagicMock(side_effect=Exception("skip"))
|
|
375
|
+
|
|
376
|
+
client = TwitterClient.__new__(TwitterClient)
|
|
377
|
+
client._ct_init_attempted = True
|
|
378
|
+
client._client_transaction = None
|
|
379
|
+
|
|
380
|
+
wrapped = {
|
|
381
|
+
"__typename": "TweetWithVisibilityResults",
|
|
382
|
+
"tweet": copy.deepcopy(self.SAMPLE_TWEET_RESULT),
|
|
383
|
+
}
|
|
384
|
+
tweet = client._parse_tweet_result(wrapped)
|
|
385
|
+
assert tweet is not None
|
|
386
|
+
assert tweet.id == "1234567890"
|
|
387
|
+
|
|
388
|
+
@patch("twitter_cli.client._get_cffi_session")
|
|
389
|
+
@patch("twitter_cli.client._gen_ct_headers", return_value={})
|
|
390
|
+
def test_depth_limit(self, mock_ct_headers, mock_session):
|
|
391
|
+
mock_session.return_value = MagicMock()
|
|
392
|
+
mock_session.return_value.get = MagicMock(side_effect=Exception("skip"))
|
|
393
|
+
|
|
394
|
+
client = TwitterClient.__new__(TwitterClient)
|
|
395
|
+
client._ct_init_attempted = True
|
|
396
|
+
client._client_transaction = None
|
|
397
|
+
|
|
398
|
+
assert client._parse_tweet_result(self.SAMPLE_TWEET_RESULT, depth=3) is None
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
# ── TwitterAPIError ──────────────────────────────────────────────────────
|
|
402
|
+
|
|
403
|
+
class TestTwitterAPIError:
|
|
404
|
+
def test_stores_status_code(self):
|
|
405
|
+
err = TwitterAPIError(429, "Rate limited")
|
|
406
|
+
assert err.status_code == 429
|
|
407
|
+
assert str(err) == "Rate limited"
|
|
408
|
+
|
|
409
|
+
def test_is_runtime_error(self):
|
|
410
|
+
err = TwitterAPIError(500, "Server error")
|
|
411
|
+
assert isinstance(err, RuntimeError)
|
|
@@ -53,7 +53,7 @@ TWITTER_OPENAPI_URL = (
|
|
|
53
53
|
"main/src/config/placeholder.json"
|
|
54
54
|
)
|
|
55
55
|
|
|
56
|
-
|
|
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
|
|
@@ -161,12 +164,18 @@ def _url_fetch(url, headers=None):
|
|
|
161
164
|
|
|
162
165
|
def _build_graphql_url(query_id, operation_name, variables, features, field_toggles=None):
|
|
163
166
|
# type: (str, str, Dict[str, Any], Dict[str, Any], Optional[Dict[str, Any]]) -> str
|
|
164
|
-
"""Build GraphQL GET URL with encoded variables/features/fieldToggles.
|
|
167
|
+
"""Build GraphQL GET URL with encoded variables/features/fieldToggles.
|
|
168
|
+
|
|
169
|
+
Only includes True-valued feature flags in the URL to avoid 414 URI Too Long.
|
|
170
|
+
Twitter's API defaults missing features to False.
|
|
171
|
+
"""
|
|
172
|
+
# Compact features: omit False values to keep URL under server limits
|
|
173
|
+
compact_features = {k: v for k, v in features.items() if v is not False}
|
|
165
174
|
url = "https://x.com/i/api/graphql/%s/%s?variables=%s&features=%s" % (
|
|
166
175
|
query_id,
|
|
167
176
|
operation_name,
|
|
168
177
|
urllib.parse.quote(json.dumps(variables, separators=(",", ":"))),
|
|
169
|
-
urllib.parse.quote(json.dumps(
|
|
178
|
+
urllib.parse.quote(json.dumps(compact_features, separators=(",", ":"))),
|
|
170
179
|
)
|
|
171
180
|
if field_toggles:
|
|
172
181
|
url += "&fieldToggles=%s" % urllib.parse.quote(
|
|
@@ -211,6 +220,35 @@ def _scan_bundles():
|
|
|
211
220
|
logger.info("Scanned %d JS bundles, cached %d query IDs", len(script_urls), len(_cached_query_ids))
|
|
212
221
|
|
|
213
222
|
|
|
223
|
+
def _update_features_from_html(html):
|
|
224
|
+
# type: (str) -> None
|
|
225
|
+
"""Extract live feature flags from x.com HTML and update the global FEATURES dict.
|
|
226
|
+
|
|
227
|
+
Twitter embeds feature switch config in inline scripts on the homepage.
|
|
228
|
+
We parse these to keep FEATURES in sync with the current frontend.
|
|
229
|
+
"""
|
|
230
|
+
try:
|
|
231
|
+
# Look for feature flags in inline script content
|
|
232
|
+
# Pattern: "featureSwitch":{"...":{"value":true/false},...}
|
|
233
|
+
# Also try: features:{key:!0, key2:!1, ...} in JS bundles
|
|
234
|
+
feature_pattern = re.compile(
|
|
235
|
+
r'"([a-z][a-z0-9_]+)":\s*\{\s*"value"\s*:\s*(true|false)',
|
|
236
|
+
re.IGNORECASE,
|
|
237
|
+
)
|
|
238
|
+
found = 0
|
|
239
|
+
for match in feature_pattern.finditer(html):
|
|
240
|
+
key = match.group(1)
|
|
241
|
+
value = match.group(2).lower() == "true"
|
|
242
|
+
# Only update keys that look like feature flags
|
|
243
|
+
if any(prefix in key for prefix in ("responsive_web_", "rweb_", "longform_", "creator_", "communities_", "c9s_")):
|
|
244
|
+
FEATURES[key] = value
|
|
245
|
+
found += 1
|
|
246
|
+
if found:
|
|
247
|
+
logger.info("Updated %d feature flags from x.com", found)
|
|
248
|
+
except Exception as exc:
|
|
249
|
+
logger.debug("Feature extraction from HTML failed: %s", exc)
|
|
250
|
+
|
|
251
|
+
|
|
214
252
|
def _fetch_from_github(operation_name):
|
|
215
253
|
# type: (str) -> Optional[str]
|
|
216
254
|
"""Fetch queryId from community-maintained twitter-openapi file."""
|
|
@@ -468,6 +506,13 @@ class TwitterClient:
|
|
|
468
506
|
|
|
469
507
|
# ── Write operations ────────────────────────────────────────────────
|
|
470
508
|
|
|
509
|
+
def _write_delay(self):
|
|
510
|
+
# type: () -> None
|
|
511
|
+
"""Sleep a random interval after write operations to avoid rate limits."""
|
|
512
|
+
delay = random.uniform(1.5, 4.0)
|
|
513
|
+
logger.debug("Write operation delay: %.1fs", delay)
|
|
514
|
+
time.sleep(delay)
|
|
515
|
+
|
|
471
516
|
def create_tweet(self, text, reply_to_id=None):
|
|
472
517
|
# type: (str, Optional[str]) -> str
|
|
473
518
|
"""Post a new tweet. Returns the new tweet ID."""
|
|
@@ -483,6 +528,7 @@ class TwitterClient:
|
|
|
483
528
|
"exclude_reply_user_ids": [],
|
|
484
529
|
}
|
|
485
530
|
data = self._graphql_post("CreateTweet", variables, FEATURES)
|
|
531
|
+
self._write_delay()
|
|
486
532
|
result = _deep_get(data, "data", "create_tweet", "tweet_results", "result")
|
|
487
533
|
if result:
|
|
488
534
|
return result.get("rest_id", "")
|
|
@@ -493,42 +539,49 @@ class TwitterClient:
|
|
|
493
539
|
"""Delete a tweet. Returns True on success."""
|
|
494
540
|
variables = {"tweet_id": tweet_id, "dark_request": False}
|
|
495
541
|
self._graphql_post("DeleteTweet", variables)
|
|
542
|
+
self._write_delay()
|
|
496
543
|
return True
|
|
497
544
|
|
|
498
545
|
def like_tweet(self, tweet_id):
|
|
499
546
|
# type: (str) -> bool
|
|
500
547
|
"""Like a tweet. Returns True on success."""
|
|
501
548
|
self._graphql_post("FavoriteTweet", {"tweet_id": tweet_id})
|
|
549
|
+
self._write_delay()
|
|
502
550
|
return True
|
|
503
551
|
|
|
504
552
|
def unlike_tweet(self, tweet_id):
|
|
505
553
|
# type: (str) -> bool
|
|
506
554
|
"""Unlike a tweet. Returns True on success."""
|
|
507
555
|
self._graphql_post("UnfavoriteTweet", {"tweet_id": tweet_id, "dark_request": False})
|
|
556
|
+
self._write_delay()
|
|
508
557
|
return True
|
|
509
558
|
|
|
510
559
|
def retweet(self, tweet_id):
|
|
511
560
|
# type: (str) -> bool
|
|
512
561
|
"""Retweet a tweet. Returns True on success."""
|
|
513
562
|
self._graphql_post("CreateRetweet", {"tweet_id": tweet_id, "dark_request": False})
|
|
563
|
+
self._write_delay()
|
|
514
564
|
return True
|
|
515
565
|
|
|
516
566
|
def unretweet(self, tweet_id):
|
|
517
567
|
# type: (str) -> bool
|
|
518
568
|
"""Undo a retweet. Returns True on success."""
|
|
519
569
|
self._graphql_post("DeleteRetweet", {"source_tweet_id": tweet_id, "dark_request": False})
|
|
570
|
+
self._write_delay()
|
|
520
571
|
return True
|
|
521
572
|
|
|
522
573
|
def bookmark_tweet(self, tweet_id):
|
|
523
574
|
# type: (str) -> bool
|
|
524
575
|
"""Bookmark a tweet. Returns True on success."""
|
|
525
576
|
self._graphql_post("CreateBookmark", {"tweet_id": tweet_id})
|
|
577
|
+
self._write_delay()
|
|
526
578
|
return True
|
|
527
579
|
|
|
528
580
|
def unbookmark_tweet(self, tweet_id):
|
|
529
581
|
# type: (str) -> bool
|
|
530
582
|
"""Remove a tweet from bookmarks. Returns True on success."""
|
|
531
583
|
self._graphql_post("DeleteBookmark", {"tweet_id": tweet_id})
|
|
584
|
+
self._write_delay()
|
|
532
585
|
return True
|
|
533
586
|
|
|
534
587
|
def _fetch_timeline(self, operation_name, count, get_instructions, extra_variables=None, override_base_variables=False, field_toggles=None):
|
|
@@ -609,7 +662,10 @@ class TwitterClient:
|
|
|
609
662
|
|
|
610
663
|
def _ensure_client_transaction(self):
|
|
611
664
|
# type: () -> None
|
|
612
|
-
"""Initialize ClientTransaction for x-client-transaction-id header.
|
|
665
|
+
"""Initialize ClientTransaction for x-client-transaction-id header.
|
|
666
|
+
|
|
667
|
+
Also attempts to extract live feature flags from JS bundles.
|
|
668
|
+
"""
|
|
613
669
|
if self._ct_init_attempted:
|
|
614
670
|
return
|
|
615
671
|
self._ct_init_attempted = True
|
|
@@ -632,6 +688,9 @@ class TwitterClient:
|
|
|
632
688
|
ondemand_file_response=ondemand_file.text,
|
|
633
689
|
)
|
|
634
690
|
logger.info("ClientTransaction initialized for x-client-transaction-id")
|
|
691
|
+
|
|
692
|
+
# Try to extract live FEATURES from the homepage JS bundles
|
|
693
|
+
_update_features_from_html(home_page.text)
|
|
635
694
|
except Exception as exc:
|
|
636
695
|
logger.warning("Failed to init ClientTransaction: %s", exc)
|
|
637
696
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|