twitter-cli 0.4.0__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.
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/PKG-INFO +3 -3
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/README.md +2 -2
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/pyproject.toml +1 -1
- twitter_cli-0.4.1/tests/test_client.py +394 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/twitter_cli/client.py +55 -2
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/uv.lock +1 -1
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/.github/workflows/ci.yml +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/.github/workflows/publish-clawhub.yml +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/.github/workflows/publish.yml +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/.gitignore +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/LICENSE +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/SKILL.md +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/config.yaml +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/tests/conftest.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/tests/test_cli.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/tests/test_config.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/tests/test_config_normalization.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/tests/test_filter.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/tests/test_serialization.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/twitter_cli/__init__.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/twitter_cli/auth.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/twitter_cli/cli.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/twitter_cli/config.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/twitter_cli/constants.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/twitter_cli/filter.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/twitter_cli/formatter.py +0 -0
- {twitter_cli-0.4.0 → twitter_cli-0.4.1}/twitter_cli/models.py +0 -0
- {twitter_cli-0.4.0 → 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.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
|
|
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,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)
|
|
@@ -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
|
|
@@ -211,6 +214,35 @@ def _scan_bundles():
|
|
|
211
214
|
logger.info("Scanned %d JS bundles, cached %d query IDs", len(script_urls), len(_cached_query_ids))
|
|
212
215
|
|
|
213
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
|
+
|
|
214
246
|
def _fetch_from_github(operation_name):
|
|
215
247
|
# type: (str) -> Optional[str]
|
|
216
248
|
"""Fetch queryId from community-maintained twitter-openapi file."""
|
|
@@ -468,6 +500,13 @@ class TwitterClient:
|
|
|
468
500
|
|
|
469
501
|
# ── Write operations ────────────────────────────────────────────────
|
|
470
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
|
+
|
|
471
510
|
def create_tweet(self, text, reply_to_id=None):
|
|
472
511
|
# type: (str, Optional[str]) -> str
|
|
473
512
|
"""Post a new tweet. Returns the new tweet ID."""
|
|
@@ -483,6 +522,7 @@ class TwitterClient:
|
|
|
483
522
|
"exclude_reply_user_ids": [],
|
|
484
523
|
}
|
|
485
524
|
data = self._graphql_post("CreateTweet", variables, FEATURES)
|
|
525
|
+
self._write_delay()
|
|
486
526
|
result = _deep_get(data, "data", "create_tweet", "tweet_results", "result")
|
|
487
527
|
if result:
|
|
488
528
|
return result.get("rest_id", "")
|
|
@@ -493,42 +533,49 @@ class TwitterClient:
|
|
|
493
533
|
"""Delete a tweet. Returns True on success."""
|
|
494
534
|
variables = {"tweet_id": tweet_id, "dark_request": False}
|
|
495
535
|
self._graphql_post("DeleteTweet", variables)
|
|
536
|
+
self._write_delay()
|
|
496
537
|
return True
|
|
497
538
|
|
|
498
539
|
def like_tweet(self, tweet_id):
|
|
499
540
|
# type: (str) -> bool
|
|
500
541
|
"""Like a tweet. Returns True on success."""
|
|
501
542
|
self._graphql_post("FavoriteTweet", {"tweet_id": tweet_id})
|
|
543
|
+
self._write_delay()
|
|
502
544
|
return True
|
|
503
545
|
|
|
504
546
|
def unlike_tweet(self, tweet_id):
|
|
505
547
|
# type: (str) -> bool
|
|
506
548
|
"""Unlike a tweet. Returns True on success."""
|
|
507
549
|
self._graphql_post("UnfavoriteTweet", {"tweet_id": tweet_id, "dark_request": False})
|
|
550
|
+
self._write_delay()
|
|
508
551
|
return True
|
|
509
552
|
|
|
510
553
|
def retweet(self, tweet_id):
|
|
511
554
|
# type: (str) -> bool
|
|
512
555
|
"""Retweet a tweet. Returns True on success."""
|
|
513
556
|
self._graphql_post("CreateRetweet", {"tweet_id": tweet_id, "dark_request": False})
|
|
557
|
+
self._write_delay()
|
|
514
558
|
return True
|
|
515
559
|
|
|
516
560
|
def unretweet(self, tweet_id):
|
|
517
561
|
# type: (str) -> bool
|
|
518
562
|
"""Undo a retweet. Returns True on success."""
|
|
519
563
|
self._graphql_post("DeleteRetweet", {"source_tweet_id": tweet_id, "dark_request": False})
|
|
564
|
+
self._write_delay()
|
|
520
565
|
return True
|
|
521
566
|
|
|
522
567
|
def bookmark_tweet(self, tweet_id):
|
|
523
568
|
# type: (str) -> bool
|
|
524
569
|
"""Bookmark a tweet. Returns True on success."""
|
|
525
570
|
self._graphql_post("CreateBookmark", {"tweet_id": tweet_id})
|
|
571
|
+
self._write_delay()
|
|
526
572
|
return True
|
|
527
573
|
|
|
528
574
|
def unbookmark_tweet(self, tweet_id):
|
|
529
575
|
# type: (str) -> bool
|
|
530
576
|
"""Remove a tweet from bookmarks. Returns True on success."""
|
|
531
577
|
self._graphql_post("DeleteBookmark", {"tweet_id": tweet_id})
|
|
578
|
+
self._write_delay()
|
|
532
579
|
return True
|
|
533
580
|
|
|
534
581
|
def _fetch_timeline(self, operation_name, count, get_instructions, extra_variables=None, override_base_variables=False, field_toggles=None):
|
|
@@ -609,7 +656,10 @@ class TwitterClient:
|
|
|
609
656
|
|
|
610
657
|
def _ensure_client_transaction(self):
|
|
611
658
|
# type: () -> None
|
|
612
|
-
"""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
|
+
"""
|
|
613
663
|
if self._ct_init_attempted:
|
|
614
664
|
return
|
|
615
665
|
self._ct_init_attempted = True
|
|
@@ -632,6 +682,9 @@ class TwitterClient:
|
|
|
632
682
|
ondemand_file_response=ondemand_file.text,
|
|
633
683
|
)
|
|
634
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)
|
|
635
688
|
except Exception as exc:
|
|
636
689
|
logger.warning("Failed to init ClientTransaction: %s", exc)
|
|
637
690
|
|
|
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
|