twitter-cli 0.8.0__tar.gz → 0.8.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.8.0 → twitter_cli-0.8.2}/.gitignore +1 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/PKG-INFO +25 -5
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/README.md +24 -4
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/SKILL.md +25 -2
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/pyproject.toml +1 -1
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/test_cli.py +105 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/test_client.py +21 -15
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/test_parser_fixtures.py +6 -9
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/auth.py +8 -2
- twitter_cli-0.8.2/twitter_cli/cache.py +66 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/cli.py +64 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/client.py +3 -27
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/constants.py +0 -5
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/formatter.py +8 -3
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/serialization.py +2 -0
- twitter_cli-0.8.2/twitter_cli/timeutil.py +71 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/uv.lock +1 -1
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/.github/ISSUE_TEMPLATE/feature_request.yml +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/.github/workflows/ci.yml +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/.github/workflows/publish-clawhub.yml +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/.github/workflows/publish.yml +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/LICENSE +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/SCHEMA.md +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/config.yaml +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/conftest.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/fixtures/followers_page.json +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/fixtures/home_timeline.json +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/fixtures/list_timeline.json +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/fixtures/search_timeline.json +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/fixtures/tweet_detail.json +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/test_auth.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/test_config.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/test_config_normalization.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/test_filter.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/test_search.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/test_serialization.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/tests/test_smoke.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/__init__.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/config.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/exceptions.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/filter.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/graphql.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/models.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/output.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/parser.py +0 -0
- {twitter_cli-0.8.0 → twitter_cli-0.8.2}/twitter_cli/search.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: twitter-cli
|
|
3
|
-
Version: 0.8.
|
|
3
|
+
Version: 0.8.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
|
|
@@ -55,7 +55,7 @@ A terminal-first CLI for Twitter/X: read timelines, bookmarks, and user profiles
|
|
|
55
55
|
- Timeline: fetch `for-you` and `following` feeds
|
|
56
56
|
- Bookmarks: list saved tweets from your account
|
|
57
57
|
- Search: find tweets by keyword with Top/Latest/Photos/Videos tabs
|
|
58
|
-
- Tweet detail: view a tweet and its replies
|
|
58
|
+
- Tweet detail: view a tweet and its replies; use `show <N>` to open tweet #N from the last list output
|
|
59
59
|
- Article: fetch a Twitter Article and export it as Markdown
|
|
60
60
|
- List timeline: fetch tweets from a Twitter List
|
|
61
61
|
- User lookup: fetch user profile, tweets, likes, followers, and following
|
|
@@ -67,7 +67,8 @@ A terminal-first CLI for Twitter/X: read timelines, bookmarks, and user profiles
|
|
|
67
67
|
> **AI Agent Tip:** Prefer `--yaml` for structured output unless a strict JSON parser is required. Non-TTY stdout defaults to YAML automatically. Use `--max` to limit results.
|
|
68
68
|
|
|
69
69
|
**Write:**
|
|
70
|
-
- Post: create new tweets and replies
|
|
70
|
+
- Post: create new tweets and replies, with optional image attachments (up to 4)
|
|
71
|
+
- Quote: quote-tweet with optional images
|
|
71
72
|
- Delete: remove your own tweets
|
|
72
73
|
- Like / Unlike: manage tweet likes
|
|
73
74
|
- Retweet / Unretweet: manage retweets
|
|
@@ -153,6 +154,11 @@ twitter tweet 1234567890
|
|
|
153
154
|
twitter tweet 1234567890 --full-text
|
|
154
155
|
twitter tweet https://x.com/user/status/1234567890
|
|
155
156
|
|
|
157
|
+
# Open tweet by index from last list output
|
|
158
|
+
twitter show 2 # Open tweet #2 from last feed/search
|
|
159
|
+
twitter show 2 --full-text # Full text in reply table
|
|
160
|
+
twitter show 2 --json # Structured output
|
|
161
|
+
|
|
156
162
|
# Twitter Article
|
|
157
163
|
twitter article 1234567890
|
|
158
164
|
twitter article https://x.com/user/article/1234567890 --json
|
|
@@ -176,7 +182,11 @@ twitter following elonmusk --max 50
|
|
|
176
182
|
|
|
177
183
|
# Write operations
|
|
178
184
|
twitter post "Hello from twitter-cli!"
|
|
185
|
+
twitter post "Hello!" --image photo.jpg # Post with image
|
|
186
|
+
twitter post "Gallery" -i a.png -i b.jpg -i c.webp # Up to 4 images
|
|
179
187
|
twitter post "reply text" --reply-to 1234567890
|
|
188
|
+
twitter reply 1234567890 "Nice!" -i screenshot.png # Reply with image
|
|
189
|
+
twitter quote 1234567890 "Look" -i chart.png # Quote with image
|
|
180
190
|
twitter post "Hello from twitter-cli!" --json
|
|
181
191
|
twitter delete 1234567890
|
|
182
192
|
twitter like 1234567890
|
|
@@ -385,7 +395,7 @@ After installation, OpenClaw can call `twitter-cli` commands directly.
|
|
|
385
395
|
- 时间线读取:支持 `for-you` 和 `following`
|
|
386
396
|
- 收藏读取:查看账号书签推文
|
|
387
397
|
- 搜索:按关键词搜索推文,支持 Top/Latest/Photos/Videos
|
|
388
|
-
-
|
|
398
|
+
- 推文详情:查看推文及其回复;用 `show <N>` 可直接打开上次列表里的第 N 条推文
|
|
389
399
|
- 文章读取:获取 Twitter 长文,并导出为 Markdown
|
|
390
400
|
- 列表时间线:获取 Twitter List 的推文
|
|
391
401
|
- 用户查询:查看用户资料、推文、点赞、粉丝和关注
|
|
@@ -395,7 +405,8 @@ After installation, OpenClaw can call `twitter-cli` commands directly.
|
|
|
395
405
|
> **AI Agent 提示:** 需要结构化输出时优先使用 `--yaml`,除非下游必须是 JSON。stdout 不是 TTY 时默认输出 YAML。用 `--max` 控制返回数量。
|
|
396
406
|
|
|
397
407
|
**写入:**
|
|
398
|
-
-
|
|
408
|
+
- 发推:发布新推文和回复,支持附带图片(最多 4 张,支持 JPEG/PNG/GIF/WebP)
|
|
409
|
+
- 引用推文:带评论的转发,也支持附带图片
|
|
399
410
|
- 删除:删除自己的推文
|
|
400
411
|
- 点赞 / 取消点赞
|
|
401
412
|
- 转推 / 取消转推
|
|
@@ -451,6 +462,11 @@ twitter search "trending" --filter # 启用排序筛选
|
|
|
451
462
|
twitter tweet 1234567890
|
|
452
463
|
twitter tweet 1234567890 --full-text
|
|
453
464
|
|
|
465
|
+
# 通过序号打开上次列表里的推文
|
|
466
|
+
twitter show 2 # 打开上次 feed/search 的第 2 条
|
|
467
|
+
twitter show 2 --full-text # 在回复表格里显示完整正文
|
|
468
|
+
twitter show 2 --json # 结构化输出
|
|
469
|
+
|
|
454
470
|
# Twitter 长文
|
|
455
471
|
twitter article 1234567890
|
|
456
472
|
twitter article https://x.com/user/article/1234567890 --json
|
|
@@ -474,7 +490,11 @@ twitter following elonmusk
|
|
|
474
490
|
|
|
475
491
|
# 写操作
|
|
476
492
|
twitter post "你好,世界!"
|
|
493
|
+
twitter post "发图" --image photo.jpg # 带图发推
|
|
494
|
+
twitter post "多图" -i a.png -i b.jpg -i c.webp # 最多 4 张图片
|
|
477
495
|
twitter post "回复内容" --reply-to 1234567890
|
|
496
|
+
twitter reply 1234567890 "回复" -i screenshot.png # 带图回复
|
|
497
|
+
twitter quote 1234567890 "评论" -i chart.png # 带图引用
|
|
478
498
|
twitter post "你好,世界!" --json
|
|
479
499
|
twitter delete 1234567890
|
|
480
500
|
twitter like 1234567890
|
|
@@ -23,7 +23,7 @@ A terminal-first CLI for Twitter/X: read timelines, bookmarks, and user profiles
|
|
|
23
23
|
- Timeline: fetch `for-you` and `following` feeds
|
|
24
24
|
- Bookmarks: list saved tweets from your account
|
|
25
25
|
- Search: find tweets by keyword with Top/Latest/Photos/Videos tabs
|
|
26
|
-
- Tweet detail: view a tweet and its replies
|
|
26
|
+
- Tweet detail: view a tweet and its replies; use `show <N>` to open tweet #N from the last list output
|
|
27
27
|
- Article: fetch a Twitter Article and export it as Markdown
|
|
28
28
|
- List timeline: fetch tweets from a Twitter List
|
|
29
29
|
- User lookup: fetch user profile, tweets, likes, followers, and following
|
|
@@ -35,7 +35,8 @@ A terminal-first CLI for Twitter/X: read timelines, bookmarks, and user profiles
|
|
|
35
35
|
> **AI Agent Tip:** Prefer `--yaml` for structured output unless a strict JSON parser is required. Non-TTY stdout defaults to YAML automatically. Use `--max` to limit results.
|
|
36
36
|
|
|
37
37
|
**Write:**
|
|
38
|
-
- Post: create new tweets and replies
|
|
38
|
+
- Post: create new tweets and replies, with optional image attachments (up to 4)
|
|
39
|
+
- Quote: quote-tweet with optional images
|
|
39
40
|
- Delete: remove your own tweets
|
|
40
41
|
- Like / Unlike: manage tweet likes
|
|
41
42
|
- Retweet / Unretweet: manage retweets
|
|
@@ -121,6 +122,11 @@ twitter tweet 1234567890
|
|
|
121
122
|
twitter tweet 1234567890 --full-text
|
|
122
123
|
twitter tweet https://x.com/user/status/1234567890
|
|
123
124
|
|
|
125
|
+
# Open tweet by index from last list output
|
|
126
|
+
twitter show 2 # Open tweet #2 from last feed/search
|
|
127
|
+
twitter show 2 --full-text # Full text in reply table
|
|
128
|
+
twitter show 2 --json # Structured output
|
|
129
|
+
|
|
124
130
|
# Twitter Article
|
|
125
131
|
twitter article 1234567890
|
|
126
132
|
twitter article https://x.com/user/article/1234567890 --json
|
|
@@ -144,7 +150,11 @@ twitter following elonmusk --max 50
|
|
|
144
150
|
|
|
145
151
|
# Write operations
|
|
146
152
|
twitter post "Hello from twitter-cli!"
|
|
153
|
+
twitter post "Hello!" --image photo.jpg # Post with image
|
|
154
|
+
twitter post "Gallery" -i a.png -i b.jpg -i c.webp # Up to 4 images
|
|
147
155
|
twitter post "reply text" --reply-to 1234567890
|
|
156
|
+
twitter reply 1234567890 "Nice!" -i screenshot.png # Reply with image
|
|
157
|
+
twitter quote 1234567890 "Look" -i chart.png # Quote with image
|
|
148
158
|
twitter post "Hello from twitter-cli!" --json
|
|
149
159
|
twitter delete 1234567890
|
|
150
160
|
twitter like 1234567890
|
|
@@ -353,7 +363,7 @@ After installation, OpenClaw can call `twitter-cli` commands directly.
|
|
|
353
363
|
- 时间线读取:支持 `for-you` 和 `following`
|
|
354
364
|
- 收藏读取:查看账号书签推文
|
|
355
365
|
- 搜索:按关键词搜索推文,支持 Top/Latest/Photos/Videos
|
|
356
|
-
-
|
|
366
|
+
- 推文详情:查看推文及其回复;用 `show <N>` 可直接打开上次列表里的第 N 条推文
|
|
357
367
|
- 文章读取:获取 Twitter 长文,并导出为 Markdown
|
|
358
368
|
- 列表时间线:获取 Twitter List 的推文
|
|
359
369
|
- 用户查询:查看用户资料、推文、点赞、粉丝和关注
|
|
@@ -363,7 +373,8 @@ After installation, OpenClaw can call `twitter-cli` commands directly.
|
|
|
363
373
|
> **AI Agent 提示:** 需要结构化输出时优先使用 `--yaml`,除非下游必须是 JSON。stdout 不是 TTY 时默认输出 YAML。用 `--max` 控制返回数量。
|
|
364
374
|
|
|
365
375
|
**写入:**
|
|
366
|
-
-
|
|
376
|
+
- 发推:发布新推文和回复,支持附带图片(最多 4 张,支持 JPEG/PNG/GIF/WebP)
|
|
377
|
+
- 引用推文:带评论的转发,也支持附带图片
|
|
367
378
|
- 删除:删除自己的推文
|
|
368
379
|
- 点赞 / 取消点赞
|
|
369
380
|
- 转推 / 取消转推
|
|
@@ -419,6 +430,11 @@ twitter search "trending" --filter # 启用排序筛选
|
|
|
419
430
|
twitter tweet 1234567890
|
|
420
431
|
twitter tweet 1234567890 --full-text
|
|
421
432
|
|
|
433
|
+
# 通过序号打开上次列表里的推文
|
|
434
|
+
twitter show 2 # 打开上次 feed/search 的第 2 条
|
|
435
|
+
twitter show 2 --full-text # 在回复表格里显示完整正文
|
|
436
|
+
twitter show 2 --json # 结构化输出
|
|
437
|
+
|
|
422
438
|
# Twitter 长文
|
|
423
439
|
twitter article 1234567890
|
|
424
440
|
twitter article https://x.com/user/article/1234567890 --json
|
|
@@ -442,7 +458,11 @@ twitter following elonmusk
|
|
|
442
458
|
|
|
443
459
|
# 写操作
|
|
444
460
|
twitter post "你好,世界!"
|
|
461
|
+
twitter post "发图" --image photo.jpg # 带图发推
|
|
462
|
+
twitter post "多图" -i a.png -i b.jpg -i c.webp # 最多 4 张图片
|
|
445
463
|
twitter post "回复内容" --reply-to 1234567890
|
|
464
|
+
twitter reply 1234567890 "回复" -i screenshot.png # 带图回复
|
|
465
|
+
twitter quote 1234567890 "评论" -i chart.png # 带图引用
|
|
446
466
|
twitter post "你好,世界!" --json
|
|
447
467
|
twitter delete 1234567890
|
|
448
468
|
twitter like 1234567890
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
name: twitter-cli
|
|
3
3
|
description: Use twitter-cli for ALL Twitter/X operations — reading tweets, posting, replying, quoting, liking, retweeting, following, searching, user lookups. Invoke whenever user requests any Twitter interaction.
|
|
4
4
|
author: jackwener
|
|
5
|
-
version: "
|
|
5
|
+
version: "0.8.0"
|
|
6
6
|
tags:
|
|
7
7
|
- twitter
|
|
8
8
|
- x
|
|
@@ -165,6 +165,9 @@ twitter search "topic" -o results.json # Save to file
|
|
|
165
165
|
twitter tweet 1234567890 # Tweet detail + replies
|
|
166
166
|
twitter tweet 1234567890 --full-text # Full text in reply table
|
|
167
167
|
twitter tweet https://x.com/user/status/12345 # Accepts URL
|
|
168
|
+
twitter show 2 # Open tweet #2 from last feed/search list
|
|
169
|
+
twitter show 2 --full-text # Full text in reply table
|
|
170
|
+
twitter show 2 --json # Structured output
|
|
168
171
|
twitter list 1539453138322673664 # List timeline
|
|
169
172
|
twitter list 1539453138322673664 --full-text
|
|
170
173
|
twitter user-posts elonmusk --max 20 # User's tweets
|
|
@@ -179,9 +182,13 @@ twitter following elonmusk --max 50 # Following
|
|
|
179
182
|
|
|
180
183
|
```bash
|
|
181
184
|
twitter post "Hello from twitter-cli!" # Post tweet
|
|
185
|
+
twitter post "Hello!" --image photo.jpg # Post with image
|
|
186
|
+
twitter post "Gallery" -i a.png -i b.jpg # Up to 4 images
|
|
182
187
|
twitter reply 1234567890 "Great tweet!" # Reply (standalone)
|
|
188
|
+
twitter reply 1234567890 "Nice!" -i pic.png # Reply with image
|
|
183
189
|
twitter post "reply text" --reply-to 1234567890 # Reply (via post)
|
|
184
190
|
twitter quote 1234567890 "Interesting take" # Quote-tweet
|
|
191
|
+
twitter quote 1234567890 "Look" -i chart.png # Quote with image
|
|
185
192
|
twitter delete 1234567890 # Delete tweet
|
|
186
193
|
twitter like 1234567890 # Like
|
|
187
194
|
twitter unlike 1234567890 # Unlike
|
|
@@ -193,6 +200,12 @@ twitter follow elonmusk # Follow user
|
|
|
193
200
|
twitter unfollow elonmusk # Unfollow user
|
|
194
201
|
```
|
|
195
202
|
|
|
203
|
+
**Image upload notes:**
|
|
204
|
+
- Supported formats: JPEG, PNG, GIF, WebP
|
|
205
|
+
- Max file size: 5 MB per image
|
|
206
|
+
- Max 4 images per tweet
|
|
207
|
+
- Use `--image` / `-i` (repeatable)
|
|
208
|
+
|
|
196
209
|
## Agent Workflows
|
|
197
210
|
|
|
198
211
|
### Post and verify
|
|
@@ -202,6 +215,16 @@ twitter post "My tweet text" 2>/dev/null
|
|
|
202
215
|
# Output includes tweet URL: 🔗 https://x.com/i/status/<id>
|
|
203
216
|
```
|
|
204
217
|
|
|
218
|
+
### Post with images
|
|
219
|
+
|
|
220
|
+
```bash
|
|
221
|
+
# Single image
|
|
222
|
+
twitter post "Check this out!" --image /path/to/photo.jpg
|
|
223
|
+
|
|
224
|
+
# Multiple images
|
|
225
|
+
twitter post "Photo gallery" -i img1.png -i img2.jpg -i img3.webp
|
|
226
|
+
```
|
|
227
|
+
|
|
205
228
|
### Reply to someone's latest tweet
|
|
206
229
|
|
|
207
230
|
```bash
|
|
@@ -306,7 +329,7 @@ twitter bookmarks --filter
|
|
|
306
329
|
|
|
307
330
|
## Limitations
|
|
308
331
|
|
|
309
|
-
- **
|
|
332
|
+
- **Images only** — video/GIF animation upload not yet supported (image upload supports JPEG/PNG/GIF/WebP)
|
|
310
333
|
- **No DMs** — no direct messaging
|
|
311
334
|
- **No notifications** — can't read notifications
|
|
312
335
|
- **No polls** — can't create polls
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
|
|
3
6
|
from click.testing import CliRunner
|
|
4
7
|
import pytest
|
|
5
8
|
from rich.console import Console
|
|
@@ -538,3 +541,105 @@ def test_cli_compact_mode(tmp_path, tweet_factory) -> None:
|
|
|
538
541
|
assert '"@alice"' in result.output
|
|
539
542
|
# Compact output should NOT have full metrics keys
|
|
540
543
|
assert '"metrics"' not in result.output
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def _write_cache(cache_file, tweets, created_at=None):
|
|
547
|
+
"""Write a test cache file."""
|
|
548
|
+
if created_at is None:
|
|
549
|
+
created_at = time.time()
|
|
550
|
+
entries = [
|
|
551
|
+
{"index": i + 1, "id": t.id, "author": t.author.screen_name, "text": t.text[:80]}
|
|
552
|
+
for i, t in enumerate(tweets)
|
|
553
|
+
]
|
|
554
|
+
payload = {"created_at": created_at, "tweets": entries}
|
|
555
|
+
cache_file.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def test_show_happy_path(monkeypatch, tmp_path, tweet_factory):
|
|
559
|
+
"""show <N> resolves cached index and fetches tweet detail."""
|
|
560
|
+
tw = tweet_factory("42", text="hello world")
|
|
561
|
+
cache_file = tmp_path / "last_results.json"
|
|
562
|
+
_write_cache(cache_file, [tweet_factory("10"), tw]) # tw is index 2
|
|
563
|
+
|
|
564
|
+
monkeypatch.setattr("twitter_cli.cache._CACHE_FILE", cache_file)
|
|
565
|
+
|
|
566
|
+
class FakeClient:
|
|
567
|
+
def fetch_tweet_detail(self, tweet_id, count):
|
|
568
|
+
assert tweet_id == "42"
|
|
569
|
+
return [tw]
|
|
570
|
+
|
|
571
|
+
monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None, quiet=False: FakeClient())
|
|
572
|
+
monkeypatch.setattr("twitter_cli.cli.load_config", lambda: {})
|
|
573
|
+
|
|
574
|
+
runner = CliRunner()
|
|
575
|
+
result = runner.invoke(cli, ["show", "2"])
|
|
576
|
+
assert result.exit_code == 0
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def test_show_empty_cache(monkeypatch, tmp_path):
|
|
580
|
+
"""show fails with a helpful message when no cache exists."""
|
|
581
|
+
cache_file = tmp_path / "last_results.json"
|
|
582
|
+
monkeypatch.setattr("twitter_cli.cache._CACHE_FILE", cache_file)
|
|
583
|
+
|
|
584
|
+
runner = CliRunner()
|
|
585
|
+
result = runner.invoke(cli, ["show", "1"])
|
|
586
|
+
assert result.exit_code != 0
|
|
587
|
+
assert "No cached results" in result.output
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def test_show_out_of_range(monkeypatch, tmp_path, tweet_factory):
|
|
591
|
+
"""show fails with out-of-range message when index exceeds cache size."""
|
|
592
|
+
cache_file = tmp_path / "last_results.json"
|
|
593
|
+
_write_cache(cache_file, [tweet_factory("1")])
|
|
594
|
+
monkeypatch.setattr("twitter_cli.cache._CACHE_FILE", cache_file)
|
|
595
|
+
|
|
596
|
+
runner = CliRunner()
|
|
597
|
+
result = runner.invoke(cli, ["show", "99"])
|
|
598
|
+
assert result.exit_code != 0
|
|
599
|
+
assert "out of range" in result.output
|
|
600
|
+
assert "1" in result.output # cache has 1 tweet
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def test_show_expired_cache(monkeypatch, tmp_path, tweet_factory):
|
|
604
|
+
"""show treats an expired cache the same as no cache."""
|
|
605
|
+
cache_file = tmp_path / "last_results.json"
|
|
606
|
+
expired_time = time.time() - 7200 # 2 hours ago
|
|
607
|
+
_write_cache(cache_file, [tweet_factory("1")], created_at=expired_time)
|
|
608
|
+
monkeypatch.setattr("twitter_cli.cache._CACHE_FILE", cache_file)
|
|
609
|
+
|
|
610
|
+
runner = CliRunner()
|
|
611
|
+
result = runner.invoke(cli, ["show", "1"])
|
|
612
|
+
assert result.exit_code != 0
|
|
613
|
+
assert "No cached results" in result.output
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def test_show_rejects_zero_index(monkeypatch, tmp_path):
|
|
617
|
+
"""show rejects index=0 because indices are 1-based."""
|
|
618
|
+
cache_file = tmp_path / "last_results.json"
|
|
619
|
+
monkeypatch.setattr("twitter_cli.cache._CACHE_FILE", cache_file)
|
|
620
|
+
|
|
621
|
+
runner = CliRunner()
|
|
622
|
+
result = runner.invoke(cli, ["show", "0"])
|
|
623
|
+
assert result.exit_code != 0
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def test_show_rejects_negative_index(monkeypatch, tmp_path):
|
|
627
|
+
"""show rejects negative indices."""
|
|
628
|
+
cache_file = tmp_path / "last_results.json"
|
|
629
|
+
monkeypatch.setattr("twitter_cli.cache._CACHE_FILE", cache_file)
|
|
630
|
+
|
|
631
|
+
runner = CliRunner()
|
|
632
|
+
result = runner.invoke(cli, ["show", "-1"])
|
|
633
|
+
assert result.exit_code != 0
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def test_show_malformed_cache_treated_as_empty(monkeypatch, tmp_path):
|
|
637
|
+
"""show handles a corrupted cache file gracefully."""
|
|
638
|
+
cache_file = tmp_path / "last_results.json"
|
|
639
|
+
cache_file.write_text("not valid json{{}", encoding="utf-8")
|
|
640
|
+
monkeypatch.setattr("twitter_cli.cache._CACHE_FILE", cache_file)
|
|
641
|
+
|
|
642
|
+
runner = CliRunner()
|
|
643
|
+
result = runner.invoke(cli, ["show", "1"])
|
|
644
|
+
assert result.exit_code != 0
|
|
645
|
+
assert "No cached results" in result.output
|
|
@@ -13,16 +13,22 @@ import pytest
|
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
from twitter_cli.client import (
|
|
16
|
-
FEATURES,
|
|
17
16
|
_best_chrome_target,
|
|
17
|
+
TwitterClient,
|
|
18
|
+
)
|
|
19
|
+
from twitter_cli.exceptions import TwitterAPIError
|
|
20
|
+
from twitter_cli.graphql import (
|
|
21
|
+
FEATURES,
|
|
18
22
|
_build_graphql_url,
|
|
23
|
+
_update_features_from_html,
|
|
24
|
+
)
|
|
25
|
+
from twitter_cli.parser import (
|
|
19
26
|
_deep_get,
|
|
20
27
|
_extract_cursor,
|
|
21
28
|
_extract_media,
|
|
22
29
|
_parse_int,
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
TwitterClient,
|
|
30
|
+
parse_tweet_result,
|
|
31
|
+
parse_user_result,
|
|
26
32
|
)
|
|
27
33
|
|
|
28
34
|
|
|
@@ -339,9 +345,9 @@ class TestPaginationBehavior:
|
|
|
339
345
|
return [MagicMock(id="tweet-1")], None
|
|
340
346
|
|
|
341
347
|
client._graphql_get = _graphql_get
|
|
342
|
-
client._parse_timeline_response = _parse_timeline_response
|
|
343
348
|
|
|
344
|
-
|
|
349
|
+
with patch('twitter_cli.client.parse_timeline_response', side_effect=_parse_timeline_response):
|
|
350
|
+
tweets = client._fetch_timeline("HomeTimeline", 1, lambda data: data)
|
|
345
351
|
|
|
346
352
|
assert [tweet.id for tweet in tweets] == ["tweet-1"]
|
|
347
353
|
|
|
@@ -357,9 +363,9 @@ class TestPaginationBehavior:
|
|
|
357
363
|
return {"page": len(calls)}
|
|
358
364
|
|
|
359
365
|
client._graphql_get = _graphql_get
|
|
360
|
-
client._parse_timeline_response = lambda data, get_instructions: ([], "cursor-same")
|
|
361
366
|
|
|
362
|
-
|
|
367
|
+
with patch('twitter_cli.client.parse_timeline_response', return_value=([], "cursor-same")):
|
|
368
|
+
tweets = client._fetch_timeline("HomeTimeline", 1, lambda data: data)
|
|
363
369
|
|
|
364
370
|
assert tweets == []
|
|
365
371
|
assert calls == [None, "cursor-same"]
|
|
@@ -401,9 +407,9 @@ class TestPaginationBehavior:
|
|
|
401
407
|
]
|
|
402
408
|
|
|
403
409
|
client._graphql_get = _graphql_get
|
|
404
|
-
client._parse_user_result = _parse_user_result
|
|
405
410
|
|
|
406
|
-
|
|
411
|
+
with patch('twitter_cli.client.parse_user_result', side_effect=_parse_user_result):
|
|
412
|
+
users = client._fetch_user_list("Followers", "1", 1, _get_instructions)
|
|
407
413
|
|
|
408
414
|
assert [user.screen_name for user in users] == ["alice"]
|
|
409
415
|
|
|
@@ -453,7 +459,7 @@ class TestParseTweetResult:
|
|
|
453
459
|
client._ct_init_attempted = True
|
|
454
460
|
client._client_transaction = None
|
|
455
461
|
|
|
456
|
-
tweet =
|
|
462
|
+
tweet = parse_tweet_result(copy.deepcopy(self.SAMPLE_TWEET_RESULT))
|
|
457
463
|
assert tweet is not None
|
|
458
464
|
assert tweet.id == "1234567890"
|
|
459
465
|
assert tweet.text == "Hello world! This is a test tweet."
|
|
@@ -475,7 +481,7 @@ class TestParseTweetResult:
|
|
|
475
481
|
client._client_transaction = None
|
|
476
482
|
|
|
477
483
|
result = {"__typename": "TweetTombstone"}
|
|
478
|
-
assert
|
|
484
|
+
assert parse_tweet_result(result) is None
|
|
479
485
|
|
|
480
486
|
@patch("twitter_cli.client._get_cffi_session")
|
|
481
487
|
@patch("twitter_cli.client._gen_ct_headers", return_value={})
|
|
@@ -491,7 +497,7 @@ class TestParseTweetResult:
|
|
|
491
497
|
"__typename": "TweetWithVisibilityResults",
|
|
492
498
|
"tweet": copy.deepcopy(self.SAMPLE_TWEET_RESULT),
|
|
493
499
|
}
|
|
494
|
-
tweet =
|
|
500
|
+
tweet = parse_tweet_result(wrapped)
|
|
495
501
|
assert tweet is not None
|
|
496
502
|
assert tweet.id == "1234567890"
|
|
497
503
|
|
|
@@ -505,7 +511,7 @@ class TestParseTweetResult:
|
|
|
505
511
|
client._ct_init_attempted = True
|
|
506
512
|
client._client_transaction = None
|
|
507
513
|
|
|
508
|
-
assert
|
|
514
|
+
assert parse_tweet_result(self.SAMPLE_TWEET_RESULT, depth=3) is None
|
|
509
515
|
|
|
510
516
|
|
|
511
517
|
# ── TwitterAPIError ──────────────────────────────────────────────────────
|
|
@@ -523,7 +529,7 @@ class TestTwitterAPIError:
|
|
|
523
529
|
|
|
524
530
|
class TestParseUserResult:
|
|
525
531
|
def test_coerces_count_fields_to_int(self):
|
|
526
|
-
user =
|
|
532
|
+
user = parse_user_result(
|
|
527
533
|
{
|
|
528
534
|
"rest_id": "user-1",
|
|
529
535
|
"legacy": {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
-
from twitter_cli.client import TwitterClient
|
|
3
|
+
from twitter_cli.client import TwitterClient
|
|
4
|
+
from twitter_cli.parser import _deep_get, parse_timeline_response
|
|
4
5
|
|
|
5
6
|
|
|
6
7
|
def _make_client() -> TwitterClient:
|
|
@@ -15,10 +16,9 @@ def _make_client() -> TwitterClient:
|
|
|
15
16
|
|
|
16
17
|
|
|
17
18
|
def test_parse_home_timeline_fixture(fixture_loader) -> None:
|
|
18
|
-
client = _make_client()
|
|
19
19
|
payload = fixture_loader("home_timeline.json")
|
|
20
20
|
|
|
21
|
-
tweets, cursor =
|
|
21
|
+
tweets, cursor = parse_timeline_response(
|
|
22
22
|
payload,
|
|
23
23
|
lambda data: _deep_get(data, "data", "home", "home_timeline_urt", "instructions"),
|
|
24
24
|
)
|
|
@@ -34,10 +34,9 @@ def test_parse_home_timeline_fixture(fixture_loader) -> None:
|
|
|
34
34
|
|
|
35
35
|
|
|
36
36
|
def test_parse_tweet_detail_fixture_with_nested_items(fixture_loader) -> None:
|
|
37
|
-
client = _make_client()
|
|
38
37
|
payload = fixture_loader("tweet_detail.json")
|
|
39
38
|
|
|
40
|
-
tweets, cursor =
|
|
39
|
+
tweets, cursor = parse_timeline_response(
|
|
41
40
|
payload,
|
|
42
41
|
lambda data: _deep_get(data, "data", "threaded_conversation_with_injections_v2", "instructions"),
|
|
43
42
|
)
|
|
@@ -47,10 +46,9 @@ def test_parse_tweet_detail_fixture_with_nested_items(fixture_loader) -> None:
|
|
|
47
46
|
|
|
48
47
|
|
|
49
48
|
def test_parse_search_timeline_fixture_with_module_items(fixture_loader) -> None:
|
|
50
|
-
client = _make_client()
|
|
51
49
|
payload = fixture_loader("search_timeline.json")
|
|
52
50
|
|
|
53
|
-
tweets, cursor =
|
|
51
|
+
tweets, cursor = parse_timeline_response(
|
|
54
52
|
payload,
|
|
55
53
|
lambda data: _deep_get(data, "data", "search_by_raw_query", "search_timeline", "timeline", "instructions"),
|
|
56
54
|
)
|
|
@@ -62,10 +60,9 @@ def test_parse_search_timeline_fixture_with_module_items(fixture_loader) -> None
|
|
|
62
60
|
|
|
63
61
|
|
|
64
62
|
def test_parse_list_timeline_fixture_with_visibility_wrapper(fixture_loader) -> None:
|
|
65
|
-
client = _make_client()
|
|
66
63
|
payload = fixture_loader("list_timeline.json")
|
|
67
64
|
|
|
68
|
-
tweets, cursor =
|
|
65
|
+
tweets, cursor = parse_timeline_response(
|
|
69
66
|
payload,
|
|
70
67
|
lambda data: _deep_get(data, "data", "list", "tweets_timeline", "timeline", "instructions"),
|
|
71
68
|
)
|
|
@@ -353,9 +353,15 @@ def iter_cookie_files(browser_name):
|
|
|
353
353
|
if sys.platform == "darwin":
|
|
354
354
|
root = os.path.join(os.path.expanduser("~"), "Library", "Application Support", base_dir)
|
|
355
355
|
elif sys.platform == "win32":
|
|
356
|
-
|
|
356
|
+
if browser_name == "edge":
|
|
357
|
+
root = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Microsoft", "Edge", "User Data")
|
|
358
|
+
else:
|
|
359
|
+
root = os.path.join(os.environ.get("LOCALAPPDATA", ""), base_dir)
|
|
357
360
|
else:
|
|
358
|
-
|
|
361
|
+
if browser_name == "edge":
|
|
362
|
+
root = os.path.join(os.path.expanduser("~"), ".config", "microsoft-edge")
|
|
363
|
+
else:
|
|
364
|
+
root = os.path.join(os.path.expanduser("~"), ".config", base_dir)
|
|
359
365
|
if not os.path.isdir(root):
|
|
360
366
|
return []
|
|
361
367
|
env_profile = os.environ.get("TWITTER_CHROME_PROFILE", "").strip()
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Short-index cache: persist the last displayed tweet list for quick `show` access."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import List, Optional, Tuple
|
|
10
|
+
|
|
11
|
+
from .models import Tweet
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
_CACHE_DIR = Path.home() / ".twitter-cli"
|
|
16
|
+
_CACHE_FILE = _CACHE_DIR / "last_results.json"
|
|
17
|
+
_TTL = 3600 # seconds
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def save_tweet_cache(tweets: List[Tweet]) -> None:
|
|
21
|
+
"""Persist tweet list so indices can be resolved by `show`."""
|
|
22
|
+
try:
|
|
23
|
+
_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
|
24
|
+
entries = [
|
|
25
|
+
{"index": i + 1, "id": t.id, "author": t.author.screen_name, "text": t.text[:80]}
|
|
26
|
+
for i, t in enumerate(tweets)
|
|
27
|
+
if t.id
|
|
28
|
+
]
|
|
29
|
+
payload = {"created_at": time.time(), "tweets": entries}
|
|
30
|
+
_CACHE_FILE.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
31
|
+
except OSError as exc:
|
|
32
|
+
logger.debug("Failed to write tweet cache: %s", exc)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _load_cache() -> Optional[List[dict]]:
|
|
36
|
+
"""Load and validate the cache file; return tweet entries or None if stale/missing."""
|
|
37
|
+
try:
|
|
38
|
+
if not _CACHE_FILE.exists():
|
|
39
|
+
return None
|
|
40
|
+
payload = json.loads(_CACHE_FILE.read_text(encoding="utf-8"))
|
|
41
|
+
if not isinstance(payload, dict):
|
|
42
|
+
return None
|
|
43
|
+
if time.time() - payload.get("created_at", 0) > _TTL:
|
|
44
|
+
return None
|
|
45
|
+
entries = payload.get("tweets", [])
|
|
46
|
+
if not isinstance(entries, list):
|
|
47
|
+
return None
|
|
48
|
+
return [e for e in entries if isinstance(e, dict)]
|
|
49
|
+
except (OSError, json.JSONDecodeError):
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def resolve_cached_tweet(index: int) -> Tuple[Optional[str], int]:
|
|
54
|
+
"""Resolve a 1-based index to a tweet ID, returning (tweet_id, cache_size).
|
|
55
|
+
|
|
56
|
+
Returns (tweet_id, cache_size) where tweet_id is None if the index
|
|
57
|
+
cannot be resolved (empty/expired cache or out-of-range index).
|
|
58
|
+
"""
|
|
59
|
+
entries = _load_cache()
|
|
60
|
+
if entries is None:
|
|
61
|
+
return None, 0
|
|
62
|
+
for entry in entries:
|
|
63
|
+
if entry.get("index") == index:
|
|
64
|
+
tweet_id = entry.get("id")
|
|
65
|
+
return (str(tweet_id) if tweet_id is not None else None), len(entries)
|
|
66
|
+
return None, len(entries)
|
|
@@ -45,6 +45,7 @@ from rich.console import Console
|
|
|
45
45
|
|
|
46
46
|
from . import __version__
|
|
47
47
|
from .auth import get_cookies
|
|
48
|
+
from .cache import resolve_cached_tweet, save_tweet_cache
|
|
48
49
|
from .client import TwitterClient
|
|
49
50
|
from .config import load_config
|
|
50
51
|
from .filter import filter_tweets
|
|
@@ -348,6 +349,8 @@ def _fetch_and_display(fetch_fn, label, emoji, max_count, as_json, as_yaml, outp
|
|
|
348
349
|
click.echo(tweets_to_compact_json(filtered))
|
|
349
350
|
return
|
|
350
351
|
|
|
352
|
+
save_tweet_cache(filtered)
|
|
353
|
+
|
|
351
354
|
if emit_structured(tweets_to_data(filtered), as_json=as_json, as_yaml=as_yaml):
|
|
352
355
|
return
|
|
353
356
|
|
|
@@ -357,6 +360,7 @@ def _fetch_and_display(fetch_fn, label, emoji, max_count, as_json, as_yaml, outp
|
|
|
357
360
|
title="%s %s — %d tweets" % (emoji, label, len(filtered)),
|
|
358
361
|
full_text=full_text,
|
|
359
362
|
)
|
|
363
|
+
_print_show_hint()
|
|
360
364
|
console.print()
|
|
361
365
|
|
|
362
366
|
|
|
@@ -440,12 +444,15 @@ def feed(ctx, feed_type, max_count, as_json, as_yaml, input_file, output_file, d
|
|
|
440
444
|
click.echo(tweets_to_compact_json(filtered))
|
|
441
445
|
return
|
|
442
446
|
|
|
447
|
+
save_tweet_cache(filtered)
|
|
448
|
+
|
|
443
449
|
if emit_structured(tweets_to_data(filtered), as_json=as_json, as_yaml=as_yaml):
|
|
444
450
|
return
|
|
445
451
|
|
|
446
452
|
title = "👥 Following" if feed_type == "following" else "📱 Twitter"
|
|
447
453
|
title += " — %d tweets" % len(filtered)
|
|
448
454
|
print_tweet_table(filtered, console, title=title, full_text=full_text)
|
|
455
|
+
_print_show_hint()
|
|
449
456
|
console.print()
|
|
450
457
|
|
|
451
458
|
|
|
@@ -699,6 +706,12 @@ def tweet(ctx, tweet_id, max_count, full_text, as_json, as_yaml):
|
|
|
699
706
|
except RuntimeError as exc:
|
|
700
707
|
_exit_with_error(exc)
|
|
701
708
|
|
|
709
|
+
_emit_tweet_detail(tweets, compact=compact, as_json=as_json, as_yaml=as_yaml, full_text=full_text)
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
def _emit_tweet_detail(tweets, compact, as_json, as_yaml, full_text):
|
|
713
|
+
# type: (list, bool, bool, bool, bool) -> None
|
|
714
|
+
"""Render tweet detail + replies in the requested output format."""
|
|
702
715
|
if compact:
|
|
703
716
|
click.echo(tweets_to_compact_json(tweets))
|
|
704
717
|
return
|
|
@@ -714,6 +727,57 @@ def tweet(ctx, tweet_id, max_count, full_text, as_json, as_yaml):
|
|
|
714
727
|
console.print()
|
|
715
728
|
|
|
716
729
|
|
|
730
|
+
def _print_show_hint():
|
|
731
|
+
# type: () -> None
|
|
732
|
+
"""Print a hint about the `show` command."""
|
|
733
|
+
console.print("[dim]💡 Use `twitter show <N>` to view tweet #N from this list.[/dim]")
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
@cli.command()
|
|
737
|
+
@click.argument("index", type=click.IntRange(1))
|
|
738
|
+
@click.option("--max", "-n", "max_count", type=int, default=None, help="Max replies to fetch.")
|
|
739
|
+
@click.option("--full-text", is_flag=True, help="Show full reply text in table output.")
|
|
740
|
+
@click.option("--output", "-o", "output_file", type=str, default=None, help="Save tweet detail as JSON to file.")
|
|
741
|
+
@structured_output_options
|
|
742
|
+
@click.pass_context
|
|
743
|
+
def show(ctx, index, max_count, full_text, output_file, as_json, as_yaml):
|
|
744
|
+
# type: (Any, int, Optional[int], bool, Optional[str], bool, bool) -> None
|
|
745
|
+
"""View tweet #INDEX from the last feed/search results."""
|
|
746
|
+
compact = ctx.obj.get("compact", False)
|
|
747
|
+
|
|
748
|
+
tweet_id, cache_size = resolve_cached_tweet(index)
|
|
749
|
+
if tweet_id is None:
|
|
750
|
+
if cache_size == 0:
|
|
751
|
+
raise click.UsageError(
|
|
752
|
+
"No cached results found. Run `twitter feed`, `twitter search`, "
|
|
753
|
+
"`twitter bookmarks`, or another list command first."
|
|
754
|
+
)
|
|
755
|
+
raise click.UsageError(
|
|
756
|
+
"Index %d is out of range (cache has %d tweets)." % (index, cache_size)
|
|
757
|
+
)
|
|
758
|
+
|
|
759
|
+
config = load_config()
|
|
760
|
+
rich_output = use_rich_output(as_json=as_json, as_yaml=as_yaml, compact=compact)
|
|
761
|
+
try:
|
|
762
|
+
client = _get_client_for_output(config, quiet=not rich_output)
|
|
763
|
+
if rich_output:
|
|
764
|
+
console.print("🐦 Fetching tweet #%d (id: %s)...\n" % (index, tweet_id))
|
|
765
|
+
start = time.time()
|
|
766
|
+
tweets = client.fetch_tweet_detail(tweet_id, _resolve_configured_count(config, max_count))
|
|
767
|
+
elapsed = time.time() - start
|
|
768
|
+
if rich_output:
|
|
769
|
+
console.print("✅ Fetched %d tweets in %.1fs\n" % (len(tweets), elapsed))
|
|
770
|
+
except RuntimeError as exc:
|
|
771
|
+
_exit_with_error(exc)
|
|
772
|
+
|
|
773
|
+
if output_file:
|
|
774
|
+
Path(output_file).write_text(tweets_to_json(tweets), encoding="utf-8")
|
|
775
|
+
if rich_output:
|
|
776
|
+
console.print("💾 Saved to %s\n" % output_file)
|
|
777
|
+
|
|
778
|
+
_emit_tweet_detail(tweets, compact=compact, as_json=as_json, as_yaml=as_yaml, full_text=full_text)
|
|
779
|
+
|
|
780
|
+
|
|
717
781
|
@cli.command()
|
|
718
782
|
@click.argument("tweet_id")
|
|
719
783
|
@structured_output_options
|
|
@@ -40,6 +40,7 @@ from .exceptions import (
|
|
|
40
40
|
TwitterAPIError,
|
|
41
41
|
)
|
|
42
42
|
from .graphql import (
|
|
43
|
+
FALLBACK_QUERY_IDS,
|
|
43
44
|
FEATURES,
|
|
44
45
|
_build_graphql_url,
|
|
45
46
|
_invalidate_query_id,
|
|
@@ -715,7 +716,7 @@ class TwitterClient:
|
|
|
715
716
|
variables["cursor"] = cursor
|
|
716
717
|
|
|
717
718
|
data = self._graphql_get(operation_name, variables, FEATURES, field_toggles=field_toggles)
|
|
718
|
-
new_tweets, next_cursor =
|
|
719
|
+
new_tweets, next_cursor = parse_timeline_response(data, get_instructions)
|
|
719
720
|
|
|
720
721
|
for tweet in new_tweets:
|
|
721
722
|
if tweet.id and tweet.id not in seen_ids:
|
|
@@ -780,7 +781,7 @@ class TwitterClient:
|
|
|
780
781
|
item = content.get("itemContent", {})
|
|
781
782
|
user_results = _deep_get(item, "user_results", "result")
|
|
782
783
|
if user_results:
|
|
783
|
-
user =
|
|
784
|
+
user = parse_user_result(user_results)
|
|
784
785
|
if user:
|
|
785
786
|
new_users.append(user)
|
|
786
787
|
elif entry_type == "TimelineTimelineCursor":
|
|
@@ -1081,28 +1082,3 @@ class TwitterClient:
|
|
|
1081
1082
|
except Exception as exc:
|
|
1082
1083
|
logger.debug("Failed to generate transaction id: %s", exc)
|
|
1083
1084
|
return headers
|
|
1084
|
-
|
|
1085
|
-
# ── Backward-compatible delegation to parser module ──────────────
|
|
1086
|
-
|
|
1087
|
-
@staticmethod
|
|
1088
|
-
def _parse_user_result(user_data):
|
|
1089
|
-
# type: (Dict[str, Any]) -> Optional[UserProfile]
|
|
1090
|
-
"""Parse a user result object into UserProfile."""
|
|
1091
|
-
return parse_user_result(user_data)
|
|
1092
|
-
|
|
1093
|
-
def _parse_tweet_result(self, result, depth=0):
|
|
1094
|
-
# type: (Dict[str, Any], int) -> Optional[Tweet]
|
|
1095
|
-
"""Parse a single TweetResult into a Tweet dataclass."""
|
|
1096
|
-
return parse_tweet_result(result, depth)
|
|
1097
|
-
|
|
1098
|
-
def _parse_timeline_response(self, data, get_instructions):
|
|
1099
|
-
# type: (Any, Callable[[Any], Any]) -> Tuple[List[Tweet], Optional[str]]
|
|
1100
|
-
"""Parse timeline GraphQL response into tweets and next cursor."""
|
|
1101
|
-
return parse_timeline_response(data, get_instructions)
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
# ── Backward compatibility re-exports ────────────────────────────────────
|
|
1105
|
-
# These keep existing test imports working without modification.
|
|
1106
|
-
|
|
1107
|
-
from .graphql import FALLBACK_QUERY_IDS # noqa: E402, F401
|
|
1108
|
-
from .parser import _extract_cursor, _extract_media # noqa: E402, F401
|
|
@@ -121,8 +121,3 @@ SEC_CH_UA_ARCH = get_sec_ch_ua_arch()
|
|
|
121
121
|
SEC_CH_UA_BITNESS = '"64"'
|
|
122
122
|
SEC_CH_UA_MODEL = '""'
|
|
123
123
|
SEC_CH_UA_PLATFORM_VERSION = get_sec_ch_ua_platform_version()
|
|
124
|
-
|
|
125
|
-
# Legacy aliases — modules that import these get the default value.
|
|
126
|
-
# _build_headers() should use get_user_agent() / get_sec_ch_ua() instead.
|
|
127
|
-
USER_AGENT = get_user_agent()
|
|
128
|
-
SEC_CH_UA = get_sec_ch_ua()
|
|
@@ -10,6 +10,7 @@ from rich.panel import Panel
|
|
|
10
10
|
from rich.table import Table
|
|
11
11
|
|
|
12
12
|
from .models import Tweet, UserProfile
|
|
13
|
+
from .timeutil import format_local_time, format_relative_time
|
|
13
14
|
|
|
14
15
|
|
|
15
16
|
def format_number(n: int) -> str:
|
|
@@ -77,13 +78,15 @@ def print_tweet_table(
|
|
|
77
78
|
text += "\n🔗 x.com/%s/status/%s" % (tweet.author.screen_name, tweet.id)
|
|
78
79
|
|
|
79
80
|
# Stats
|
|
81
|
+
rel_time = format_relative_time(tweet.created_at)
|
|
80
82
|
stats = (
|
|
81
|
-
"❤️ %s 🔄 %s\n💬 %s 👁️ %s"
|
|
83
|
+
"❤️ %s 🔄 %s\n💬 %s 👁️ %s\n🕐 %s"
|
|
82
84
|
% (
|
|
83
85
|
format_number(tweet.metrics.likes),
|
|
84
86
|
format_number(tweet.metrics.retweets),
|
|
85
87
|
format_number(tweet.metrics.replies),
|
|
86
88
|
format_number(tweet.metrics.views),
|
|
89
|
+
rel_time,
|
|
87
90
|
)
|
|
88
91
|
)
|
|
89
92
|
|
|
@@ -138,9 +141,11 @@ def print_tweet_detail(tweet: Tweet, console: Optional[Console] = None) -> None:
|
|
|
138
141
|
format_number(tweet.metrics.views),
|
|
139
142
|
)
|
|
140
143
|
)
|
|
144
|
+
local_time = format_local_time(tweet.created_at)
|
|
145
|
+
rel_time = format_relative_time(tweet.created_at)
|
|
141
146
|
body_parts.append(
|
|
142
|
-
"🕐 %s · https://x.com/%s/status/%s"
|
|
143
|
-
% (
|
|
147
|
+
"🕐 %s (%s) · https://x.com/%s/status/%s"
|
|
148
|
+
% (local_time, rel_time, tweet.author.screen_name, tweet.id)
|
|
144
149
|
)
|
|
145
150
|
|
|
146
151
|
console.print(Panel(
|
|
@@ -6,6 +6,7 @@ import json
|
|
|
6
6
|
from typing import Any, Dict, Iterable, List, Optional
|
|
7
7
|
|
|
8
8
|
from .models import Author, Metrics, Tweet, TweetMedia, UserProfile
|
|
9
|
+
from .timeutil import format_local_time
|
|
9
10
|
|
|
10
11
|
|
|
11
12
|
def tweet_to_dict(tweet: Tweet) -> Dict[str, Any]:
|
|
@@ -29,6 +30,7 @@ def tweet_to_dict(tweet: Tweet) -> Dict[str, Any]:
|
|
|
29
30
|
"bookmarks": tweet.metrics.bookmarks,
|
|
30
31
|
},
|
|
31
32
|
"createdAt": tweet.created_at,
|
|
33
|
+
"createdAtLocal": format_local_time(tweet.created_at),
|
|
32
34
|
"media": [
|
|
33
35
|
{
|
|
34
36
|
"type": media.type,
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Time formatting utilities for twitter-cli.
|
|
2
|
+
|
|
3
|
+
Converts Twitter API timestamps (e.g. "Sat Mar 08 12:00:00 +0000 2026")
|
|
4
|
+
into human-friendly local time and relative time strings.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
# Twitter API timestamp format: "Sat Mar 08 12:00:00 +0000 2026"
|
|
16
|
+
_TWITTER_TIME_FORMAT = "%a %b %d %H:%M:%S %z %Y"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _parse_twitter_time(created_at: str) -> Optional[datetime]:
|
|
20
|
+
"""Parse a Twitter API timestamp into a timezone-aware datetime."""
|
|
21
|
+
if not created_at:
|
|
22
|
+
return None
|
|
23
|
+
try:
|
|
24
|
+
return datetime.strptime(created_at, _TWITTER_TIME_FORMAT)
|
|
25
|
+
except (ValueError, TypeError):
|
|
26
|
+
logger.debug("Failed to parse Twitter timestamp: %s", created_at)
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def format_local_time(created_at: str) -> str:
|
|
31
|
+
"""Convert Twitter timestamp to local time string.
|
|
32
|
+
|
|
33
|
+
Returns "2026-03-14 21:08" or the original string on parse failure.
|
|
34
|
+
"""
|
|
35
|
+
dt = _parse_twitter_time(created_at)
|
|
36
|
+
if dt is None:
|
|
37
|
+
return created_at
|
|
38
|
+
local_dt = dt.astimezone()
|
|
39
|
+
return local_dt.strftime("%Y-%m-%d %H:%M")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def format_relative_time(created_at: str) -> str:
|
|
43
|
+
"""Convert Twitter timestamp to a relative time string.
|
|
44
|
+
|
|
45
|
+
Returns e.g. "2m ago", "3h ago", "5d ago", or the original string on failure.
|
|
46
|
+
"""
|
|
47
|
+
dt = _parse_twitter_time(created_at)
|
|
48
|
+
if dt is None:
|
|
49
|
+
return created_at
|
|
50
|
+
now = datetime.now(timezone.utc)
|
|
51
|
+
delta = now - dt
|
|
52
|
+
seconds = int(delta.total_seconds())
|
|
53
|
+
|
|
54
|
+
if seconds < 0:
|
|
55
|
+
return "just now"
|
|
56
|
+
if seconds < 60:
|
|
57
|
+
return "%ds ago" % seconds
|
|
58
|
+
minutes = seconds // 60
|
|
59
|
+
if minutes < 60:
|
|
60
|
+
return "%dm ago" % minutes
|
|
61
|
+
hours = minutes // 60
|
|
62
|
+
if hours < 24:
|
|
63
|
+
return "%dh ago" % hours
|
|
64
|
+
days = hours // 24
|
|
65
|
+
if days < 30:
|
|
66
|
+
return "%dd ago" % days
|
|
67
|
+
months = days // 30
|
|
68
|
+
if months < 12:
|
|
69
|
+
return "%dmo ago" % months
|
|
70
|
+
years = days // 365
|
|
71
|
+
return "%dy ago" % years
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|