twitter-cli 0.7.1__tar.gz → 0.8.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.7.1 → twitter_cli-0.8.1}/.gitignore +1 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/PKG-INFO +25 -5
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/README.md +24 -4
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/SKILL.md +25 -2
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/pyproject.toml +1 -1
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/test_cli.py +108 -3
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/test_client.py +143 -0
- twitter_cli-0.8.1/twitter_cli/cache.py +66 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/cli.py +104 -11
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/client.py +111 -8
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/exceptions.py +4 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/uv.lock +1 -1
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/.github/ISSUE_TEMPLATE/feature_request.yml +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/.github/workflows/ci.yml +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/.github/workflows/publish-clawhub.yml +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/.github/workflows/publish.yml +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/LICENSE +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/SCHEMA.md +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/config.yaml +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/conftest.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/fixtures/followers_page.json +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/fixtures/home_timeline.json +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/fixtures/list_timeline.json +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/fixtures/search_timeline.json +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/fixtures/tweet_detail.json +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/test_auth.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/test_config.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/test_config_normalization.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/test_filter.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/test_parser_fixtures.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/test_search.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/test_serialization.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/tests/test_smoke.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/__init__.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/auth.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/config.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/constants.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/filter.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/formatter.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/graphql.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/models.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/output.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/parser.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/search.py +0 -0
- {twitter_cli-0.7.1 → twitter_cli-0.8.1}/twitter_cli/serialization.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: twitter-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.8.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
|
|
@@ -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
|
|
@@ -321,7 +324,7 @@ def test_cli_reply_command(monkeypatch) -> None:
|
|
|
321
324
|
calls = []
|
|
322
325
|
|
|
323
326
|
class FakeClient:
|
|
324
|
-
def create_tweet(self, text: str, reply_to_id=None) -> str:
|
|
327
|
+
def create_tweet(self, text: str, reply_to_id=None, media_ids=None) -> str:
|
|
325
328
|
calls.append({"text": text, "reply_to_id": reply_to_id})
|
|
326
329
|
return "999"
|
|
327
330
|
|
|
@@ -338,7 +341,7 @@ def test_cli_quote_command(monkeypatch) -> None:
|
|
|
338
341
|
calls = []
|
|
339
342
|
|
|
340
343
|
class FakeClient:
|
|
341
|
-
def quote_tweet(self, tweet_id: str, text: str) -> str:
|
|
344
|
+
def quote_tweet(self, tweet_id: str, text: str, media_ids=None) -> str:
|
|
342
345
|
calls.append({"tweet_id": tweet_id, "text": text})
|
|
343
346
|
return "888"
|
|
344
347
|
|
|
@@ -353,7 +356,7 @@ def test_cli_quote_command(monkeypatch) -> None:
|
|
|
353
356
|
|
|
354
357
|
def test_cli_post_json_output(monkeypatch) -> None:
|
|
355
358
|
class FakeClient:
|
|
356
|
-
def create_tweet(self, text: str, reply_to_id=None) -> str:
|
|
359
|
+
def create_tweet(self, text: str, reply_to_id=None, media_ids=None) -> str:
|
|
357
360
|
assert text == "hello"
|
|
358
361
|
assert reply_to_id is None
|
|
359
362
|
return "999"
|
|
@@ -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
|
|
@@ -9,6 +9,8 @@ from __future__ import annotations
|
|
|
9
9
|
import copy
|
|
10
10
|
from unittest.mock import MagicMock, patch
|
|
11
11
|
|
|
12
|
+
import pytest
|
|
13
|
+
|
|
12
14
|
|
|
13
15
|
from twitter_cli.client import (
|
|
14
16
|
FEATURES,
|
|
@@ -540,3 +542,144 @@ class TestParseUserResult:
|
|
|
540
542
|
assert user.following_count == 56
|
|
541
543
|
assert user.tweets_count == 78
|
|
542
544
|
assert user.likes_count == 0
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
# ── upload_media ─────────────────────────────────────────────────────────
|
|
548
|
+
|
|
549
|
+
class TestUploadMedia:
|
|
550
|
+
"""Tests for TwitterClient.upload_media()."""
|
|
551
|
+
|
|
552
|
+
def _make_client(self):
|
|
553
|
+
client = TwitterClient.__new__(TwitterClient)
|
|
554
|
+
client._auth_token = "tok"
|
|
555
|
+
client._ct0 = "ct0"
|
|
556
|
+
client._cookie_string = None
|
|
557
|
+
client._request_delay = 0
|
|
558
|
+
client._max_retries = 3
|
|
559
|
+
client._retry_base_delay = 5.0
|
|
560
|
+
client._max_count = 200
|
|
561
|
+
client._client_transaction = None
|
|
562
|
+
client._ct_init_attempted = True
|
|
563
|
+
return client
|
|
564
|
+
|
|
565
|
+
@patch("twitter_cli.client._get_cffi_session")
|
|
566
|
+
def test_upload_media_init_append_finalize(self, mock_session, tmp_path):
|
|
567
|
+
"""Happy path: INIT → APPEND → FINALIZE returns media_id."""
|
|
568
|
+
img = tmp_path / "photo.jpg"
|
|
569
|
+
img.write_bytes(b"\xff\xd8\xff\xe0" + b"\x00" * 100) # fake JPEG
|
|
570
|
+
|
|
571
|
+
mock_resp_init = MagicMock()
|
|
572
|
+
mock_resp_init.status_code = 200
|
|
573
|
+
mock_resp_init.text = '{"media_id_string": "12345"}'
|
|
574
|
+
|
|
575
|
+
mock_resp_append = MagicMock()
|
|
576
|
+
mock_resp_append.status_code = 200
|
|
577
|
+
mock_resp_append.text = ""
|
|
578
|
+
|
|
579
|
+
mock_resp_finalize = MagicMock()
|
|
580
|
+
mock_resp_finalize.status_code = 200
|
|
581
|
+
mock_resp_finalize.text = '{"media_id_string": "12345"}'
|
|
582
|
+
|
|
583
|
+
sess = MagicMock()
|
|
584
|
+
sess.post = MagicMock(side_effect=[mock_resp_init, mock_resp_append, mock_resp_finalize])
|
|
585
|
+
mock_session.return_value = sess
|
|
586
|
+
|
|
587
|
+
client = self._make_client()
|
|
588
|
+
media_id = client.upload_media(str(img))
|
|
589
|
+
|
|
590
|
+
assert media_id == "12345"
|
|
591
|
+
assert sess.post.call_count == 3
|
|
592
|
+
|
|
593
|
+
def test_upload_media_file_not_found(self):
|
|
594
|
+
from twitter_cli.exceptions import MediaUploadError
|
|
595
|
+
|
|
596
|
+
client = self._make_client()
|
|
597
|
+
with pytest.raises(MediaUploadError, match="File not found"):
|
|
598
|
+
client.upload_media("/nonexistent/file.jpg")
|
|
599
|
+
|
|
600
|
+
def test_upload_media_too_large(self, tmp_path):
|
|
601
|
+
from twitter_cli.exceptions import MediaUploadError
|
|
602
|
+
|
|
603
|
+
img = tmp_path / "big.jpg"
|
|
604
|
+
img.write_bytes(b"\xff\xd8\xff\xe0" + b"\x00" * (6 * 1024 * 1024)) # 6 MB
|
|
605
|
+
|
|
606
|
+
client = self._make_client()
|
|
607
|
+
with pytest.raises(MediaUploadError, match="File too large"):
|
|
608
|
+
client.upload_media(str(img))
|
|
609
|
+
|
|
610
|
+
def test_upload_media_unsupported_format(self, tmp_path):
|
|
611
|
+
from twitter_cli.exceptions import MediaUploadError
|
|
612
|
+
|
|
613
|
+
txt = tmp_path / "notes.txt"
|
|
614
|
+
txt.write_text("hello")
|
|
615
|
+
|
|
616
|
+
client = self._make_client()
|
|
617
|
+
with pytest.raises(MediaUploadError, match="Unsupported image format"):
|
|
618
|
+
client.upload_media(str(txt))
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
# ── create_tweet with media_ids ──────────────────────────────────────────
|
|
622
|
+
|
|
623
|
+
class TestCreateTweetWithMedia:
|
|
624
|
+
"""Tests that media_ids are correctly passed into CreateTweet variables."""
|
|
625
|
+
|
|
626
|
+
@patch("twitter_cli.client._get_cffi_session")
|
|
627
|
+
def test_create_tweet_with_media_ids(self, mock_session):
|
|
628
|
+
sess = MagicMock()
|
|
629
|
+
mock_session.return_value = sess
|
|
630
|
+
|
|
631
|
+
client = TwitterClient.__new__(TwitterClient)
|
|
632
|
+
client._auth_token = "tok"
|
|
633
|
+
client._ct0 = "ct0"
|
|
634
|
+
client._cookie_string = None
|
|
635
|
+
client._request_delay = 0
|
|
636
|
+
client._max_retries = 0
|
|
637
|
+
client._retry_base_delay = 0
|
|
638
|
+
client._max_count = 200
|
|
639
|
+
client._client_transaction = None
|
|
640
|
+
client._ct_init_attempted = True
|
|
641
|
+
|
|
642
|
+
captured_body = {}
|
|
643
|
+
|
|
644
|
+
def mock_graphql_post(operation_name, variables, features=None):
|
|
645
|
+
captured_body.update(variables)
|
|
646
|
+
return {"data": {"create_tweet": {"tweet_results": {"result": {"rest_id": "99"}}}}}
|
|
647
|
+
|
|
648
|
+
client._graphql_post = mock_graphql_post
|
|
649
|
+
|
|
650
|
+
result = client.create_tweet("test", media_ids=["111", "222"])
|
|
651
|
+
assert result == "99"
|
|
652
|
+
|
|
653
|
+
entities = captured_body["media"]["media_entities"]
|
|
654
|
+
assert len(entities) == 2
|
|
655
|
+
assert entities[0]["media_id"] == "111"
|
|
656
|
+
assert entities[1]["media_id"] == "222"
|
|
657
|
+
|
|
658
|
+
@patch("twitter_cli.client._get_cffi_session")
|
|
659
|
+
def test_create_tweet_without_media_ids(self, mock_session):
|
|
660
|
+
sess = MagicMock()
|
|
661
|
+
mock_session.return_value = sess
|
|
662
|
+
|
|
663
|
+
client = TwitterClient.__new__(TwitterClient)
|
|
664
|
+
client._auth_token = "tok"
|
|
665
|
+
client._ct0 = "ct0"
|
|
666
|
+
client._cookie_string = None
|
|
667
|
+
client._request_delay = 0
|
|
668
|
+
client._max_retries = 0
|
|
669
|
+
client._retry_base_delay = 0
|
|
670
|
+
client._max_count = 200
|
|
671
|
+
client._client_transaction = None
|
|
672
|
+
client._ct_init_attempted = True
|
|
673
|
+
|
|
674
|
+
captured_body = {}
|
|
675
|
+
|
|
676
|
+
def mock_graphql_post(operation_name, variables, features=None):
|
|
677
|
+
captured_body.update(variables)
|
|
678
|
+
return {"data": {"create_tweet": {"tweet_results": {"result": {"rest_id": "88"}}}}}
|
|
679
|
+
|
|
680
|
+
client._graphql_post = mock_graphql_post
|
|
681
|
+
|
|
682
|
+
result = client.create_tweet("no media")
|
|
683
|
+
assert result == "88"
|
|
684
|
+
assert captured_body["media"]["media_entities"] == []
|
|
685
|
+
|
|
@@ -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)
|
|
@@ -18,6 +18,7 @@ Read commands:
|
|
|
18
18
|
|
|
19
19
|
Write commands:
|
|
20
20
|
twitter post "text" # post a tweet
|
|
21
|
+
twitter post "text" -i photo.jpg # post with image(s)
|
|
21
22
|
twitter reply <id> "text" # reply to a tweet
|
|
22
23
|
twitter quote <id> "text" # quote-tweet
|
|
23
24
|
twitter delete <id> # delete a tweet
|
|
@@ -44,6 +45,7 @@ from rich.console import Console
|
|
|
44
45
|
|
|
45
46
|
from . import __version__
|
|
46
47
|
from .auth import get_cookies
|
|
48
|
+
from .cache import resolve_cached_tweet, save_tweet_cache
|
|
47
49
|
from .client import TwitterClient
|
|
48
50
|
from .config import load_config
|
|
49
51
|
from .filter import filter_tweets
|
|
@@ -347,6 +349,8 @@ def _fetch_and_display(fetch_fn, label, emoji, max_count, as_json, as_yaml, outp
|
|
|
347
349
|
click.echo(tweets_to_compact_json(filtered))
|
|
348
350
|
return
|
|
349
351
|
|
|
352
|
+
save_tweet_cache(filtered)
|
|
353
|
+
|
|
350
354
|
if emit_structured(tweets_to_data(filtered), as_json=as_json, as_yaml=as_yaml):
|
|
351
355
|
return
|
|
352
356
|
|
|
@@ -356,6 +360,7 @@ def _fetch_and_display(fetch_fn, label, emoji, max_count, as_json, as_yaml, outp
|
|
|
356
360
|
title="%s %s — %d tweets" % (emoji, label, len(filtered)),
|
|
357
361
|
full_text=full_text,
|
|
358
362
|
)
|
|
363
|
+
_print_show_hint()
|
|
359
364
|
console.print()
|
|
360
365
|
|
|
361
366
|
|
|
@@ -439,12 +444,15 @@ def feed(ctx, feed_type, max_count, as_json, as_yaml, input_file, output_file, d
|
|
|
439
444
|
click.echo(tweets_to_compact_json(filtered))
|
|
440
445
|
return
|
|
441
446
|
|
|
447
|
+
save_tweet_cache(filtered)
|
|
448
|
+
|
|
442
449
|
if emit_structured(tweets_to_data(filtered), as_json=as_json, as_yaml=as_yaml):
|
|
443
450
|
return
|
|
444
451
|
|
|
445
452
|
title = "👥 Following" if feed_type == "following" else "📱 Twitter"
|
|
446
453
|
title += " — %d tweets" % len(filtered)
|
|
447
454
|
print_tweet_table(filtered, console, title=title, full_text=full_text)
|
|
455
|
+
_print_show_hint()
|
|
448
456
|
console.print()
|
|
449
457
|
|
|
450
458
|
|
|
@@ -698,6 +706,12 @@ def tweet(ctx, tweet_id, max_count, full_text, as_json, as_yaml):
|
|
|
698
706
|
except RuntimeError as exc:
|
|
699
707
|
_exit_with_error(exc)
|
|
700
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."""
|
|
701
715
|
if compact:
|
|
702
716
|
click.echo(tweets_to_compact_json(tweets))
|
|
703
717
|
return
|
|
@@ -713,6 +727,51 @@ def tweet(ctx, tweet_id, max_count, full_text, as_json, as_yaml):
|
|
|
713
727
|
console.print()
|
|
714
728
|
|
|
715
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
|
+
@structured_output_options
|
|
741
|
+
@click.pass_context
|
|
742
|
+
def show(ctx, index, max_count, full_text, as_json, as_yaml):
|
|
743
|
+
# type: (Any, int, Optional[int], bool, bool, bool) -> None
|
|
744
|
+
"""View tweet #INDEX from the last feed/search results."""
|
|
745
|
+
compact = ctx.obj.get("compact", False)
|
|
746
|
+
|
|
747
|
+
tweet_id, cache_size = resolve_cached_tweet(index)
|
|
748
|
+
if tweet_id is None:
|
|
749
|
+
if cache_size == 0:
|
|
750
|
+
raise click.UsageError(
|
|
751
|
+
"No cached results found. Run `twitter feed`, `twitter search`, "
|
|
752
|
+
"`twitter bookmarks`, or another list command first."
|
|
753
|
+
)
|
|
754
|
+
raise click.UsageError(
|
|
755
|
+
"Index %d is out of range (cache has %d tweets)." % (index, cache_size)
|
|
756
|
+
)
|
|
757
|
+
|
|
758
|
+
config = load_config()
|
|
759
|
+
rich_output = use_rich_output(as_json=as_json, as_yaml=as_yaml, compact=compact)
|
|
760
|
+
try:
|
|
761
|
+
client = _get_client_for_output(config, quiet=not rich_output)
|
|
762
|
+
if rich_output:
|
|
763
|
+
console.print("🐦 Fetching tweet #%d (id: %s)...\n" % (index, tweet_id))
|
|
764
|
+
start = time.time()
|
|
765
|
+
tweets = client.fetch_tweet_detail(tweet_id, _resolve_configured_count(config, max_count))
|
|
766
|
+
elapsed = time.time() - start
|
|
767
|
+
if rich_output:
|
|
768
|
+
console.print("✅ Fetched %d tweets in %.1fs\n" % (len(tweets), elapsed))
|
|
769
|
+
except RuntimeError as exc:
|
|
770
|
+
_exit_with_error(exc)
|
|
771
|
+
|
|
772
|
+
_emit_tweet_detail(tweets, compact=compact, as_json=as_json, as_yaml=as_yaml, full_text=full_text)
|
|
773
|
+
|
|
774
|
+
|
|
716
775
|
@cli.command()
|
|
717
776
|
@click.argument("tweet_id")
|
|
718
777
|
@structured_output_options
|
|
@@ -849,6 +908,24 @@ def following(screen_name, max_count, as_json, as_yaml):
|
|
|
849
908
|
|
|
850
909
|
# ── Write commands ──────────────────────────────────────────────────────
|
|
851
910
|
|
|
911
|
+
_MAX_IMAGES = 4 # Twitter allows up to 4 images per tweet
|
|
912
|
+
|
|
913
|
+
|
|
914
|
+
def _upload_images(client, image_paths, rich_output=True):
|
|
915
|
+
# type: (TwitterClient, tuple, bool) -> list
|
|
916
|
+
"""Upload images and return list of media_id strings."""
|
|
917
|
+
if not image_paths:
|
|
918
|
+
return []
|
|
919
|
+
if len(image_paths) > _MAX_IMAGES:
|
|
920
|
+
raise click.UsageError("Too many images: max %d, got %d" % (_MAX_IMAGES, len(image_paths)))
|
|
921
|
+
media_ids = []
|
|
922
|
+
for i, path in enumerate(image_paths, 1):
|
|
923
|
+
if rich_output:
|
|
924
|
+
console.print("📤 Uploading image %d/%d: %s" % (i, len(image_paths), path))
|
|
925
|
+
media_ids.append(client.upload_media(path))
|
|
926
|
+
return media_ids
|
|
927
|
+
|
|
928
|
+
|
|
852
929
|
def _write_action(emoji, action_desc, client_method, tweet_id, as_json=False, as_yaml=False):
|
|
853
930
|
# type: (str, str, str, str, bool, bool) -> None
|
|
854
931
|
"""Generic write action helper to reduce CLI command boilerplate.
|
|
@@ -874,14 +951,24 @@ def _write_action(emoji, action_desc, client_method, tweet_id, as_json=False, as
|
|
|
874
951
|
@cli.command()
|
|
875
952
|
@click.argument("text")
|
|
876
953
|
@click.option("--reply-to", "-r", default=None, help="Reply to this tweet ID.")
|
|
954
|
+
@click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True), help="Attach image (up to 4). Repeatable.")
|
|
877
955
|
@structured_output_options
|
|
878
|
-
def post(text, reply_to, as_json, as_yaml):
|
|
879
|
-
# type: (str, Optional[str], bool, bool) -> None
|
|
880
|
-
"""Post a new tweet. TEXT is the tweet content.
|
|
956
|
+
def post(text, reply_to, images, as_json, as_yaml):
|
|
957
|
+
# type: (str, Optional[str], tuple, bool, bool) -> None
|
|
958
|
+
"""Post a new tweet. TEXT is the tweet content.
|
|
959
|
+
|
|
960
|
+
Attach images with --image / -i (up to 4):
|
|
961
|
+
|
|
962
|
+
\b
|
|
963
|
+
twitter post "Hello!" --image photo.jpg
|
|
964
|
+
twitter post "Gallery" -i a.png -i b.png -i c.jpg
|
|
965
|
+
"""
|
|
881
966
|
action = "Replying to %s" % reply_to if reply_to else "Posting tweet"
|
|
967
|
+
rich_output = not _structured_mode(as_json=as_json, as_yaml=as_yaml)
|
|
882
968
|
|
|
883
969
|
def operation(client: TwitterClient) -> WritePayload:
|
|
884
|
-
|
|
970
|
+
media_ids = _upload_images(client, images, rich_output=rich_output)
|
|
971
|
+
tweet_id = client.create_tweet(text, reply_to_id=reply_to, media_ids=media_ids or None)
|
|
885
972
|
return {"success": True, "action": "post", "id": tweet_id, "url": "https://x.com/i/status/%s" % tweet_id}
|
|
886
973
|
|
|
887
974
|
payload = _run_write_command(
|
|
@@ -899,13 +986,16 @@ def post(text, reply_to, as_json, as_yaml):
|
|
|
899
986
|
@cli.command(name="reply")
|
|
900
987
|
@click.argument("tweet_id")
|
|
901
988
|
@click.argument("text")
|
|
989
|
+
@click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True), help="Attach image (up to 4). Repeatable.")
|
|
902
990
|
@structured_output_options
|
|
903
|
-
def reply_tweet(tweet_id, text, as_json, as_yaml):
|
|
904
|
-
# type: (str, str, bool, bool) -> None
|
|
991
|
+
def reply_tweet(tweet_id, text, images, as_json, as_yaml):
|
|
992
|
+
# type: (str, str, tuple, bool, bool) -> None
|
|
905
993
|
"""Reply to a tweet. TWEET_ID is the tweet to reply to, TEXT is the reply content."""
|
|
906
994
|
tweet_id = _normalize_tweet_id(tweet_id)
|
|
995
|
+
rich_output = not _structured_mode(as_json=as_json, as_yaml=as_yaml)
|
|
907
996
|
def operation(client: TwitterClient) -> WritePayload:
|
|
908
|
-
|
|
997
|
+
media_ids = _upload_images(client, images, rich_output=rich_output)
|
|
998
|
+
new_id = client.create_tweet(text, reply_to_id=tweet_id, media_ids=media_ids or None)
|
|
909
999
|
return {
|
|
910
1000
|
"success": True,
|
|
911
1001
|
"action": "reply",
|
|
@@ -929,13 +1019,16 @@ def reply_tweet(tweet_id, text, as_json, as_yaml):
|
|
|
929
1019
|
@cli.command(name="quote")
|
|
930
1020
|
@click.argument("tweet_id")
|
|
931
1021
|
@click.argument("text")
|
|
1022
|
+
@click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True), help="Attach image (up to 4). Repeatable.")
|
|
932
1023
|
@structured_output_options
|
|
933
|
-
def quote_tweet(tweet_id, text, as_json, as_yaml):
|
|
934
|
-
# type: (str, str, bool, bool) -> None
|
|
1024
|
+
def quote_tweet(tweet_id, text, images, as_json, as_yaml):
|
|
1025
|
+
# type: (str, str, tuple, bool, bool) -> None
|
|
935
1026
|
"""Quote-tweet a tweet. TWEET_ID is the tweet to quote, TEXT is the commentary."""
|
|
936
1027
|
tweet_id = _normalize_tweet_id(tweet_id)
|
|
1028
|
+
rich_output = not _structured_mode(as_json=as_json, as_yaml=as_yaml)
|
|
937
1029
|
def operation(client: TwitterClient) -> WritePayload:
|
|
938
|
-
|
|
1030
|
+
media_ids = _upload_images(client, images, rich_output=rich_output)
|
|
1031
|
+
new_id = client.quote_tweet(tweet_id, text, media_ids=media_ids or None)
|
|
939
1032
|
return {
|
|
940
1033
|
"success": True,
|
|
941
1034
|
"action": "quote",
|
|
@@ -953,7 +1046,7 @@ def quote_tweet(tweet_id, text, as_json, as_yaml):
|
|
|
953
1046
|
error_details={"action": "quote", "quotedId": tweet_id},
|
|
954
1047
|
)
|
|
955
1048
|
if payload and not _structured_mode(as_json=as_json, as_yaml=as_yaml):
|
|
956
|
-
console.print("🔗 %s" % payload["url"])
|
|
1049
|
+
console.print("🔗 %s" % payload["url"])
|
|
957
1050
|
|
|
958
1051
|
|
|
959
1052
|
@cli.command(name="status")
|
|
@@ -2,9 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import base64
|
|
5
6
|
import json
|
|
6
7
|
import logging
|
|
7
8
|
import math
|
|
9
|
+
import mimetypes
|
|
8
10
|
import os
|
|
9
11
|
import random
|
|
10
12
|
import time
|
|
@@ -33,6 +35,7 @@ from .constants import (
|
|
|
33
35
|
sync_chrome_version,
|
|
34
36
|
)
|
|
35
37
|
from .exceptions import (
|
|
38
|
+
MediaUploadError,
|
|
36
39
|
NotFoundError,
|
|
37
40
|
TwitterAPIError,
|
|
38
41
|
)
|
|
@@ -394,6 +397,10 @@ class TwitterClient:
|
|
|
394
397
|
|
|
395
398
|
# ── Write operations ─────────────────────────────────────────────
|
|
396
399
|
|
|
400
|
+
# Supported image MIME types and max file size (5 MB)
|
|
401
|
+
_SUPPORTED_IMAGE_TYPES = {"image/jpeg", "image/png", "image/gif", "image/webp"}
|
|
402
|
+
_MAX_IMAGE_SIZE = 5 * 1024 * 1024 # 5 MB
|
|
403
|
+
|
|
397
404
|
def _write_delay(self):
|
|
398
405
|
# type: () -> None
|
|
399
406
|
"""Sleep a random interval after write operations to avoid rate limits."""
|
|
@@ -401,12 +408,99 @@ class TwitterClient:
|
|
|
401
408
|
logger.debug("Write operation delay: %.1fs", delay)
|
|
402
409
|
time.sleep(delay)
|
|
403
410
|
|
|
404
|
-
def
|
|
405
|
-
# type: (str
|
|
406
|
-
"""
|
|
411
|
+
def upload_media(self, file_path):
|
|
412
|
+
# type: (str) -> str
|
|
413
|
+
"""Upload an image file to Twitter. Returns the media_id string.
|
|
414
|
+
|
|
415
|
+
Uses Twitter's chunked upload API (INIT → APPEND → FINALIZE).
|
|
416
|
+
Supports JPEG, PNG, GIF, and WebP images up to 5 MB.
|
|
417
|
+
"""
|
|
418
|
+
if not os.path.isfile(file_path):
|
|
419
|
+
raise MediaUploadError("File not found: %s" % file_path)
|
|
420
|
+
|
|
421
|
+
file_size = os.path.getsize(file_path)
|
|
422
|
+
if file_size > self._MAX_IMAGE_SIZE:
|
|
423
|
+
raise MediaUploadError(
|
|
424
|
+
"File too large: %.1f MB (max %.0f MB)"
|
|
425
|
+
% (file_size / (1024 * 1024), self._MAX_IMAGE_SIZE / (1024 * 1024))
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
media_type = mimetypes.guess_type(file_path)[0] or ""
|
|
429
|
+
if media_type not in self._SUPPORTED_IMAGE_TYPES:
|
|
430
|
+
raise MediaUploadError(
|
|
431
|
+
"Unsupported image format: %s (supported: jpeg, png, gif, webp)" % media_type
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
upload_url = "https://upload.twitter.com/i/media/upload.json"
|
|
435
|
+
session = _get_cffi_session()
|
|
436
|
+
|
|
437
|
+
# ── INIT ─────────────────────────────────────────────────────
|
|
438
|
+
headers = self._build_headers(url=upload_url, method="POST")
|
|
439
|
+
headers["Content-Type"] = "application/x-www-form-urlencoded"
|
|
440
|
+
init_data = {
|
|
441
|
+
"command": "INIT",
|
|
442
|
+
"total_bytes": str(file_size),
|
|
443
|
+
"media_type": media_type,
|
|
444
|
+
}
|
|
445
|
+
resp = session.post(upload_url, headers=headers, data=init_data, timeout=30)
|
|
446
|
+
if resp.status_code >= 400:
|
|
447
|
+
raise MediaUploadError("INIT failed (HTTP %d): %s" % (resp.status_code, resp.text[:300]))
|
|
448
|
+
try:
|
|
449
|
+
init_result = json.loads(resp.text)
|
|
450
|
+
except (json.JSONDecodeError, ValueError):
|
|
451
|
+
raise MediaUploadError("INIT returned invalid JSON")
|
|
452
|
+
media_id = init_result.get("media_id_string", "")
|
|
453
|
+
if not media_id:
|
|
454
|
+
raise MediaUploadError("INIT did not return media_id")
|
|
455
|
+
logger.info("Media INIT: media_id=%s", media_id)
|
|
456
|
+
|
|
457
|
+
# ── APPEND ───────────────────────────────────────────────────
|
|
458
|
+
with open(file_path, "rb") as f:
|
|
459
|
+
media_data = base64.b64encode(f.read()).decode("ascii")
|
|
460
|
+
|
|
461
|
+
headers = self._build_headers(url=upload_url, method="POST")
|
|
462
|
+
# Remove JSON content-type — curl_cffi handles multipart encoding
|
|
463
|
+
headers.pop("Content-Type", None)
|
|
464
|
+
append_data = {
|
|
465
|
+
"command": "APPEND",
|
|
466
|
+
"media_id": media_id,
|
|
467
|
+
"segment_index": "0",
|
|
468
|
+
"media_data": media_data,
|
|
469
|
+
}
|
|
470
|
+
resp = session.post(upload_url, headers=headers, data=append_data, timeout=60)
|
|
471
|
+
if resp.status_code >= 400:
|
|
472
|
+
raise MediaUploadError("APPEND failed (HTTP %d): %s" % (resp.status_code, resp.text[:300]))
|
|
473
|
+
logger.info("Media APPEND: segment 0 uploaded")
|
|
474
|
+
|
|
475
|
+
# ── FINALIZE ─────────────────────────────────────────────────
|
|
476
|
+
headers = self._build_headers(url=upload_url, method="POST")
|
|
477
|
+
headers["Content-Type"] = "application/x-www-form-urlencoded"
|
|
478
|
+
finalize_data = {
|
|
479
|
+
"command": "FINALIZE",
|
|
480
|
+
"media_id": media_id,
|
|
481
|
+
}
|
|
482
|
+
resp = session.post(upload_url, headers=headers, data=finalize_data, timeout=30)
|
|
483
|
+
if resp.status_code >= 400:
|
|
484
|
+
raise MediaUploadError("FINALIZE failed (HTTP %d): %s" % (resp.status_code, resp.text[:300]))
|
|
485
|
+
logger.info("Media FINALIZE: media_id=%s ready", media_id)
|
|
486
|
+
|
|
487
|
+
return media_id
|
|
488
|
+
|
|
489
|
+
def create_tweet(self, text, reply_to_id=None, media_ids=None):
|
|
490
|
+
# type: (str, Optional[str], Optional[List[str]]) -> str
|
|
491
|
+
"""Post a new tweet. Returns the new tweet ID.
|
|
492
|
+
|
|
493
|
+
Args:
|
|
494
|
+
text: Tweet text content.
|
|
495
|
+
reply_to_id: Optional tweet ID to reply to.
|
|
496
|
+
media_ids: Optional list of media IDs (from upload_media) to attach.
|
|
497
|
+
"""
|
|
498
|
+
media_entities = []
|
|
499
|
+
if media_ids:
|
|
500
|
+
media_entities = [{"media_id": mid, "tagged_users": []} for mid in media_ids]
|
|
407
501
|
variables = {
|
|
408
502
|
"tweet_text": text,
|
|
409
|
-
"media": {"media_entities":
|
|
503
|
+
"media": {"media_entities": media_entities, "possibly_sensitive": False},
|
|
410
504
|
"semantic_annotation_ids": [],
|
|
411
505
|
"dark_request": False,
|
|
412
506
|
} # type: Dict[str, Any]
|
|
@@ -526,13 +620,22 @@ class TwitterClient:
|
|
|
526
620
|
|
|
527
621
|
raise TwitterAPIError(0, "Failed to fetch current user info")
|
|
528
622
|
|
|
529
|
-
def quote_tweet(self, tweet_id, text):
|
|
530
|
-
# type: (str, str) -> str
|
|
531
|
-
"""Quote-tweet a tweet. Returns the new tweet ID.
|
|
623
|
+
def quote_tweet(self, tweet_id, text, media_ids=None):
|
|
624
|
+
# type: (str, str, Optional[List[str]]) -> str
|
|
625
|
+
"""Quote-tweet a tweet. Returns the new tweet ID.
|
|
626
|
+
|
|
627
|
+
Args:
|
|
628
|
+
tweet_id: The tweet ID to quote.
|
|
629
|
+
text: Commentary text.
|
|
630
|
+
media_ids: Optional list of media IDs (from upload_media) to attach.
|
|
631
|
+
"""
|
|
632
|
+
media_entities = []
|
|
633
|
+
if media_ids:
|
|
634
|
+
media_entities = [{"media_id": mid, "tagged_users": []} for mid in media_ids]
|
|
532
635
|
variables = {
|
|
533
636
|
"tweet_text": text,
|
|
534
637
|
"attachment_url": "https://x.com/i/status/%s" % tweet_id,
|
|
535
|
-
"media": {"media_entities":
|
|
638
|
+
"media": {"media_entities": media_entities, "possibly_sensitive": False},
|
|
536
639
|
"semantic_annotation_ids": [],
|
|
537
640
|
"dark_request": False,
|
|
538
641
|
}
|
|
@@ -36,6 +36,10 @@ class QueryIdError(TwitterError):
|
|
|
36
36
|
"""Raised when a GraphQL queryId cannot be resolved."""
|
|
37
37
|
|
|
38
38
|
|
|
39
|
+
class MediaUploadError(TwitterError):
|
|
40
|
+
"""Raised when media upload fails (file not found, too large, unsupported format, API error)."""
|
|
41
|
+
|
|
42
|
+
|
|
39
43
|
class TwitterAPIError(TwitterError):
|
|
40
44
|
"""Raised on non-OK Twitter API responses with HTTP status + message."""
|
|
41
45
|
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|