twitter-cli 0.6.5__tar.gz → 0.7.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/PKG-INFO +15 -1
  2. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/README.md +14 -0
  3. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/SCHEMA.md +14 -0
  4. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/pyproject.toml +1 -1
  5. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/conftest.py +2 -0
  6. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/test_cli.py +164 -2
  7. twitter_cli-0.7.0/tests/test_search.py +86 -0
  8. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/test_serialization.py +13 -0
  9. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/twitter_cli/cli.py +107 -7
  10. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/twitter_cli/client.py +39 -0
  11. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/twitter_cli/formatter.py +56 -0
  12. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/twitter_cli/graphql.py +1 -0
  13. twitter_cli-0.7.0/twitter_cli/search.py +79 -0
  14. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/uv.lock +1 -1
  15. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
  16. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/.github/ISSUE_TEMPLATE/feature_request.yml +0 -0
  17. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/.github/workflows/ci.yml +0 -0
  18. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/.github/workflows/publish-clawhub.yml +0 -0
  19. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/.github/workflows/publish.yml +0 -0
  20. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/.gitignore +0 -0
  21. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/LICENSE +0 -0
  22. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/SKILL.md +0 -0
  23. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/config.yaml +0 -0
  24. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/fixtures/followers_page.json +0 -0
  25. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/fixtures/home_timeline.json +0 -0
  26. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/fixtures/list_timeline.json +0 -0
  27. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/fixtures/search_timeline.json +0 -0
  28. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/fixtures/tweet_detail.json +0 -0
  29. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/test_auth.py +0 -0
  30. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/test_client.py +0 -0
  31. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/test_config.py +0 -0
  32. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/test_config_normalization.py +0 -0
  33. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/test_filter.py +0 -0
  34. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/test_parser_fixtures.py +0 -0
  35. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/tests/test_smoke.py +0 -0
  36. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/twitter_cli/__init__.py +0 -0
  37. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/twitter_cli/auth.py +0 -0
  38. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/twitter_cli/config.py +0 -0
  39. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/twitter_cli/constants.py +0 -0
  40. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/twitter_cli/exceptions.py +0 -0
  41. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/twitter_cli/filter.py +0 -0
  42. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/twitter_cli/models.py +0 -0
  43. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/twitter_cli/output.py +0 -0
  44. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/twitter_cli/parser.py +0 -0
  45. {twitter_cli-0.6.5 → twitter_cli-0.7.0}/twitter_cli/serialization.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: twitter-cli
3
- Version: 0.6.5
3
+ Version: 0.7.0
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
@@ -56,6 +56,7 @@ A terminal-first CLI for Twitter/X: read timelines, bookmarks, and user profiles
56
56
  - Bookmarks: list saved tweets from your account
57
57
  - Search: find tweets by keyword with Top/Latest/Photos/Videos tabs
58
58
  - Tweet detail: view a tweet and its replies
59
+ - Article: fetch a Twitter Article and export it as Markdown
59
60
  - List timeline: fetch tweets from a Twitter List
60
61
  - User lookup: fetch user profile, tweets, likes, followers, and following
61
62
  - `--full-text`: disable tweet text truncation in rich table output
@@ -149,6 +150,12 @@ twitter tweet 1234567890
149
150
  twitter tweet 1234567890 --full-text
150
151
  twitter tweet https://x.com/user/status/1234567890
151
152
 
153
+ # Twitter Article
154
+ twitter article 1234567890
155
+ twitter article https://x.com/user/article/1234567890 --json
156
+ twitter article 1234567890 --markdown
157
+ twitter article 1234567890 --output article.md
158
+
152
159
  # List timeline
153
160
  twitter list 1539453138322673664
154
161
  twitter list 1539453138322673664 --full-text
@@ -376,6 +383,7 @@ After installation, OpenClaw can call `twitter-cli` commands directly.
376
383
  - 收藏读取:查看账号书签推文
377
384
  - 搜索:按关键词搜索推文,支持 Top/Latest/Photos/Videos
378
385
  - 推文详情:查看推文及其回复
386
+ - 文章读取:获取 Twitter 长文,并导出为 Markdown
379
387
  - 列表时间线:获取 Twitter List 的推文
380
388
  - 用户查询:查看用户资料、推文、点赞、粉丝和关注
381
389
  - `--full-text`:在 rich table 输出里关闭推文正文截断
@@ -440,6 +448,12 @@ twitter search "trending" --filter # 启用排序筛选
440
448
  twitter tweet 1234567890
441
449
  twitter tweet 1234567890 --full-text
442
450
 
451
+ # Twitter 长文
452
+ twitter article 1234567890
453
+ twitter article https://x.com/user/article/1234567890 --json
454
+ twitter article 1234567890 --markdown
455
+ twitter article 1234567890 --output article.md
456
+
443
457
  # 列表时间线
444
458
  twitter list 1539453138322673664
445
459
  twitter list 1539453138322673664 --full-text
@@ -24,6 +24,7 @@ A terminal-first CLI for Twitter/X: read timelines, bookmarks, and user profiles
24
24
  - Bookmarks: list saved tweets from your account
25
25
  - Search: find tweets by keyword with Top/Latest/Photos/Videos tabs
26
26
  - Tweet detail: view a tweet and its replies
27
+ - Article: fetch a Twitter Article and export it as Markdown
27
28
  - List timeline: fetch tweets from a Twitter List
28
29
  - User lookup: fetch user profile, tweets, likes, followers, and following
29
30
  - `--full-text`: disable tweet text truncation in rich table output
@@ -117,6 +118,12 @@ twitter tweet 1234567890
117
118
  twitter tweet 1234567890 --full-text
118
119
  twitter tweet https://x.com/user/status/1234567890
119
120
 
121
+ # Twitter Article
122
+ twitter article 1234567890
123
+ twitter article https://x.com/user/article/1234567890 --json
124
+ twitter article 1234567890 --markdown
125
+ twitter article 1234567890 --output article.md
126
+
120
127
  # List timeline
121
128
  twitter list 1539453138322673664
122
129
  twitter list 1539453138322673664 --full-text
@@ -344,6 +351,7 @@ After installation, OpenClaw can call `twitter-cli` commands directly.
344
351
  - 收藏读取:查看账号书签推文
345
352
  - 搜索:按关键词搜索推文,支持 Top/Latest/Photos/Videos
346
353
  - 推文详情:查看推文及其回复
354
+ - 文章读取:获取 Twitter 长文,并导出为 Markdown
347
355
  - 列表时间线:获取 Twitter List 的推文
348
356
  - 用户查询:查看用户资料、推文、点赞、粉丝和关注
349
357
  - `--full-text`:在 rich table 输出里关闭推文正文截断
@@ -408,6 +416,12 @@ twitter search "trending" --filter # 启用排序筛选
408
416
  twitter tweet 1234567890
409
417
  twitter tweet 1234567890 --full-text
410
418
 
419
+ # Twitter 长文
420
+ twitter article 1234567890
421
+ twitter article https://x.com/user/article/1234567890 --json
422
+ twitter article 1234567890 --markdown
423
+ twitter article 1234567890 --output article.md
424
+
411
425
  # 列表时间线
412
426
  twitter list 1539453138322673664
413
427
  twitter list 1539453138322673664 --full-text
@@ -25,10 +25,24 @@ error:
25
25
  - `--yaml` and `--json` both use this envelope
26
26
  - non-TTY stdout defaults to YAML
27
27
  - tweet and user lists are returned under `data`
28
+ - `article` returns a single tweet object under `data`
28
29
  - `status` returns `data.authenticated` plus `data.user`
29
30
  - `whoami` returns `data.user`
30
31
  - write commands also support explicit `--json` / `--yaml`
31
32
 
33
+ ## Article Fields
34
+
35
+ `twitter article <id> --json` returns the standard tweet object plus:
36
+
37
+ ```yaml
38
+ data:
39
+ id: "1234567890"
40
+ articleTitle: "Article Title"
41
+ articleText: |
42
+ # Heading
43
+ Body text...
44
+ ```
45
+
32
46
  ## Error Codes
33
47
 
34
48
  Common structured error codes:
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "twitter-cli"
7
- version = "0.6.5"
7
+ version = "0.7.0"
8
8
  description = "A CLI for Twitter/X — feed, bookmarks, and user timeline in terminal"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -36,6 +36,8 @@ def tweet_factory():
36
36
  retweeted_by=overrides.pop("retweeted_by", None),
37
37
  quoted_tweet=overrides.pop("quoted_tweet", None),
38
38
  score=overrides.pop("score", 0.0),
39
+ article_title=overrides.pop("article_title", None),
40
+ article_text=overrides.pop("article_text", None),
39
41
  )
40
42
 
41
43
  return _make_tweet
@@ -6,8 +6,8 @@ from rich.console import Console
6
6
  import yaml
7
7
 
8
8
  from twitter_cli.cli import cli
9
- from twitter_cli.formatter import print_tweet_table
10
- from twitter_cli.models import UserProfile
9
+ from twitter_cli.formatter import article_to_markdown, print_tweet_table
10
+ from twitter_cli.models import Author, Metrics, Tweet, UserProfile
11
11
  from twitter_cli.serialization import tweets_to_json
12
12
 
13
13
 
@@ -125,6 +125,104 @@ def test_cli_tweet_accepts_shared_url_with_query(monkeypatch) -> None:
125
125
  assert result.exit_code == 0
126
126
 
127
127
 
128
+ def test_cli_article_accepts_article_url_and_json(monkeypatch) -> None:
129
+ class FakeClient:
130
+ def fetch_article(self, tweet_id: str) -> Tweet:
131
+ assert tweet_id == "12345"
132
+ return Tweet(
133
+ id="12345",
134
+ text="https://t.co/article",
135
+ author=Author(id="u1", name="Alice", screen_name="alice"),
136
+ metrics=Metrics(likes=1, retweets=2, replies=3, views=4, bookmarks=5),
137
+ created_at="2026-03-11",
138
+ article_title="Title",
139
+ article_text="Hello\n\n## Section",
140
+ )
141
+
142
+ monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None: FakeClient())
143
+ monkeypatch.setattr(
144
+ "twitter_cli.cli.load_config",
145
+ lambda: {"fetch": {"count": 50}, "filter": {}, "rateLimit": {}},
146
+ )
147
+ runner = CliRunner()
148
+
149
+ result = runner.invoke(cli, ["article", "https://x.com/user/article/12345?s=20", "--json"])
150
+
151
+ assert result.exit_code == 0
152
+ payload = yaml.safe_load(result.output)
153
+ assert payload["ok"] is True
154
+ assert payload["data"]["id"] == "12345"
155
+ assert payload["data"]["articleTitle"] == "Title"
156
+ assert "Hello" in payload["data"]["articleText"]
157
+
158
+
159
+ def test_cli_article_markdown_output_and_save(monkeypatch, tmp_path) -> None:
160
+ article = Tweet(
161
+ id="12345",
162
+ text="https://t.co/article",
163
+ author=Author(id="u1", name="Alice", screen_name="alice"),
164
+ metrics=Metrics(likes=1, retweets=2, replies=3, views=4, bookmarks=5),
165
+ created_at="2026-03-11",
166
+ article_title="Title",
167
+ article_text="Hello\n\n## Section",
168
+ )
169
+
170
+ class FakeClient:
171
+ def fetch_article(self, tweet_id: str) -> Tweet:
172
+ assert tweet_id == "12345"
173
+ return article
174
+
175
+ monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None: FakeClient())
176
+ monkeypatch.setattr("twitter_cli.cli.load_config", lambda: {})
177
+ output_path = tmp_path / "article.md"
178
+ runner = CliRunner()
179
+
180
+ result = runner.invoke(
181
+ cli,
182
+ ["article", "12345", "--markdown", "--output", str(output_path)],
183
+ )
184
+
185
+ assert result.exit_code == 0
186
+ assert result.output == article_to_markdown(article)
187
+ assert output_path.read_text(encoding="utf-8") == article_to_markdown(article)
188
+
189
+
190
+ def test_cli_article_markdown_overrides_auto_structured_output(monkeypatch) -> None:
191
+ article = Tweet(
192
+ id="12345",
193
+ text="https://t.co/article",
194
+ author=Author(id="u1", name="Alice", screen_name="alice"),
195
+ metrics=Metrics(likes=1, retweets=2, replies=3, views=4, bookmarks=5),
196
+ created_at="2026-03-11",
197
+ article_title="Title",
198
+ article_text="Hello\n\n## Section",
199
+ )
200
+
201
+ class FakeClient:
202
+ def fetch_article(self, tweet_id: str) -> Tweet:
203
+ assert tweet_id == "12345"
204
+ return article
205
+
206
+ monkeypatch.setenv("OUTPUT", "auto")
207
+ monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None: FakeClient())
208
+ monkeypatch.setattr("twitter_cli.cli.load_config", lambda: {})
209
+ runner = CliRunner()
210
+
211
+ result = runner.invoke(cli, ["article", "12345", "--markdown"])
212
+
213
+ assert result.exit_code == 0
214
+ assert result.output == article_to_markdown(article)
215
+
216
+
217
+ def test_cli_article_rejects_compact_mode() -> None:
218
+ runner = CliRunner()
219
+
220
+ result = runner.invoke(cli, ["-c", "article", "12345"])
221
+
222
+ assert result.exit_code == 2
223
+ assert "does not support --compact" in result.output
224
+
225
+
128
226
  def test_cli_bookmark_alias_works(monkeypatch) -> None:
129
227
  calls = []
130
228
 
@@ -327,6 +425,70 @@ def test_cli_unfollow_command(monkeypatch) -> None:
327
425
  assert actions == [("unfollow", "42")]
328
426
 
329
427
 
428
+ def test_cli_search_advanced_options(monkeypatch) -> None:
429
+ captured = {}
430
+
431
+ class FakeClient:
432
+ def fetch_search(self, query: str, count: int, product: str):
433
+ captured["query"] = query
434
+ captured["product"] = product
435
+ return []
436
+
437
+ monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None: FakeClient())
438
+ monkeypatch.setattr(
439
+ "twitter_cli.cli.load_config",
440
+ lambda: {"fetch": {"count": 50}, "filter": {}, "rateLimit": {}},
441
+ )
442
+ runner = CliRunner()
443
+
444
+ result = runner.invoke(cli, [
445
+ "search", "python",
446
+ "--from", "elonmusk",
447
+ "--lang", "en",
448
+ "--since", "2026-01-01",
449
+ "--has", "links",
450
+ "--exclude", "retweets",
451
+ "--min-likes", "100",
452
+ "-t", "Latest",
453
+ "--json",
454
+ ])
455
+
456
+ assert result.exit_code == 0, f"search failed: {result.output}"
457
+ assert captured["query"] == (
458
+ "python from:elonmusk lang:en since:2026-01-01 "
459
+ "filter:links -filter:retweets min_faves:100"
460
+ )
461
+ assert captured["product"] == "Latest"
462
+
463
+
464
+ def test_cli_search_operators_only_no_query(monkeypatch) -> None:
465
+ captured = {}
466
+
467
+ class FakeClient:
468
+ def fetch_search(self, query: str, count: int, product: str):
469
+ captured["query"] = query
470
+ return []
471
+
472
+ monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None: FakeClient())
473
+ monkeypatch.setattr(
474
+ "twitter_cli.cli.load_config",
475
+ lambda: {"fetch": {"count": 50}, "filter": {}, "rateLimit": {}},
476
+ )
477
+ runner = CliRunner()
478
+
479
+ result = runner.invoke(cli, ["search", "--from", "bbc", "--json"])
480
+ assert result.exit_code == 0, f"search failed: {result.output}"
481
+ assert captured["query"] == "from:bbc"
482
+
483
+
484
+ def test_cli_search_empty_query_no_options() -> None:
485
+ runner = CliRunner()
486
+
487
+ result = runner.invoke(cli, ["search"])
488
+ assert result.exit_code != 0
489
+ assert "Provide a QUERY" in result.output
490
+
491
+
330
492
  def test_cli_compact_mode(tmp_path, tweet_factory) -> None:
331
493
  json_path = tmp_path / "tweets.json"
332
494
  json_path.write_text(tweets_to_json([tweet_factory("1")]), encoding="utf-8")
@@ -0,0 +1,86 @@
1
+ """Unit tests for the advanced search query builder."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from twitter_cli.search import build_search_query
6
+
7
+
8
+ class TestBuildSearchQuery:
9
+ def test_plain_query(self) -> None:
10
+ assert build_search_query("python") == "python"
11
+
12
+ def test_empty_query(self) -> None:
13
+ assert build_search_query("") == ""
14
+
15
+ def test_from_user(self) -> None:
16
+ assert build_search_query("AI", from_user="elonmusk") == "AI from:elonmusk"
17
+
18
+ def test_from_user_strips_at(self) -> None:
19
+ assert build_search_query("AI", from_user="@elonmusk") == "AI from:elonmusk"
20
+
21
+ def test_to_user(self) -> None:
22
+ assert build_search_query("hello", to_user="jack") == "hello to:jack"
23
+
24
+ def test_lang(self) -> None:
25
+ assert build_search_query("news", lang="fr") == "news lang:fr"
26
+
27
+ def test_since(self) -> None:
28
+ assert build_search_query("python", since="2026-01-01") == "python since:2026-01-01"
29
+
30
+ def test_until(self) -> None:
31
+ assert build_search_query("python", until="2026-03-01") == "python until:2026-03-01"
32
+
33
+ def test_date_range(self) -> None:
34
+ result = build_search_query("rust", since="2026-01-01", until="2026-03-01")
35
+ assert result == "rust since:2026-01-01 until:2026-03-01"
36
+
37
+ def test_has_links(self) -> None:
38
+ assert build_search_query("python", has=["links"]) == "python filter:links"
39
+
40
+ def test_has_multiple(self) -> None:
41
+ result = build_search_query("art", has=["images", "videos"])
42
+ assert result == "art filter:images filter:videos"
43
+
44
+ def test_exclude_retweets(self) -> None:
45
+ assert build_search_query("news", exclude=["retweets"]) == "news -filter:retweets"
46
+
47
+ def test_exclude_replies(self) -> None:
48
+ assert build_search_query("news", exclude=["replies"]) == "news -filter:replies"
49
+
50
+ def test_exclude_multiple(self) -> None:
51
+ result = build_search_query("news", exclude=["retweets", "replies"])
52
+ assert result == "news -filter:retweets -filter:replies"
53
+
54
+ def test_min_likes(self) -> None:
55
+ assert build_search_query("python", min_likes=100) == "python min_faves:100"
56
+
57
+ def test_min_retweets(self) -> None:
58
+ assert build_search_query("python", min_retweets=50) == "python min_retweets:50"
59
+
60
+ def test_combined_operators(self) -> None:
61
+ result = build_search_query(
62
+ "machine learning",
63
+ from_user="openai",
64
+ lang="en",
65
+ since="2026-01-01",
66
+ has=["links"],
67
+ min_likes=50,
68
+ exclude=["retweets"],
69
+ )
70
+ assert result == (
71
+ "machine learning from:openai lang:en since:2026-01-01 "
72
+ "filter:links -filter:retweets min_faves:50"
73
+ )
74
+
75
+ def test_operators_only_no_query(self) -> None:
76
+ result = build_search_query("", from_user="elonmusk", since="2026-03-01")
77
+ assert result == "from:elonmusk since:2026-03-01"
78
+
79
+ def test_whitespace_query_trimmed(self) -> None:
80
+ assert build_search_query(" python ", lang="en") == "python lang:en"
81
+
82
+ def test_empty_has_list(self) -> None:
83
+ assert build_search_query("test", has=[]) == "test"
84
+
85
+ def test_empty_exclude_list(self) -> None:
86
+ assert build_search_query("test", exclude=[]) == "test"
@@ -49,3 +49,16 @@ def test_compact_serialization(tweet_factory) -> None:
49
49
  assert len(parsed) == 1
50
50
  assert parsed[0]["author"] == "@alice"
51
51
 
52
+
53
+ def test_tweet_roundtrip_preserves_article_fields(tweet_factory) -> None:
54
+ tweet = tweet_factory(
55
+ "88",
56
+ article_title="Long-form title",
57
+ article_text="Intro\n\n## Details",
58
+ )
59
+
60
+ payload = tweet_to_dict(tweet)
61
+ restored = tweet_from_dict(payload)
62
+
63
+ assert restored.article_title == "Long-form title"
64
+ assert restored.article_text == "Intro\n\n## Details"
@@ -5,10 +5,12 @@ Read commands:
5
5
  twitter feed -t following # following feed
6
6
  twitter bookmarks # bookmarks
7
7
  twitter search "query" # search tweets
8
+ twitter search "query" --from user # advanced search
8
9
  twitter user elonmusk # user profile
9
10
  twitter user-posts elonmusk # user tweets
10
11
  twitter likes elonmusk # user likes
11
12
  twitter tweet <id> # tweet detail + replies
13
+ twitter article <id> # Twitter Article as Markdown
12
14
  twitter list <id> # list timeline
13
15
  twitter followers <handle> # followers list
14
16
  twitter following <handle> # following list
@@ -46,7 +48,9 @@ from .client import TwitterClient
46
48
  from .config import load_config
47
49
  from .filter import filter_tweets
48
50
  from .formatter import (
51
+ article_to_markdown,
49
52
  print_filter_stats,
53
+ print_article,
50
54
  print_tweet_detail,
51
55
  print_tweet_table,
52
56
  print_user_profile,
@@ -63,6 +67,7 @@ from .output import (
63
67
  use_rich_output,
64
68
  )
65
69
  from .serialization import (
70
+ tweet_to_dict,
66
71
  tweets_from_json,
67
72
  tweets_to_data,
68
73
  tweets_to_compact_json,
@@ -83,6 +88,8 @@ logger = logging.getLogger(__name__)
83
88
  console = Console(stderr=True)
84
89
  FEED_TYPES = ["for-you", "following"]
85
90
  SEARCH_PRODUCTS = ["Top", "Latest", "Photos", "Videos"]
91
+ SEARCH_HAS_CHOICES = ["links", "images", "videos", "media"]
92
+ SEARCH_EXCLUDE_CHOICES = ["retweets", "replies", "links"]
86
93
 
87
94
 
88
95
  def _agent_user_profile(profile: UserProfile) -> dict:
@@ -214,7 +221,7 @@ def _normalize_tweet_id(value):
214
221
  candidate = raw
215
222
  if parsed.scheme and parsed.netloc:
216
223
  path = parsed.path.rstrip("/")
217
- match = re.search(r"/status/(\d+)$", path)
224
+ match = re.search(r"/(?:status|article)/(\d+)$", path)
218
225
  if not match:
219
226
  raise RuntimeError("Invalid tweet URL: %s" % value)
220
227
  candidate = match.group(1)
@@ -533,7 +540,7 @@ def user_posts(ctx, screen_name, max_count, as_json, as_yaml, output_file, full_
533
540
 
534
541
 
535
542
  @cli.command()
536
- @click.argument("query")
543
+ @click.argument("query", default="")
537
544
  @click.option(
538
545
  "--type",
539
546
  "-t",
@@ -542,23 +549,70 @@ def user_posts(ctx, screen_name, max_count, as_json, as_yaml, output_file, full_
542
549
  default="Top",
543
550
  help="Search tab: Top, Latest, Photos, or Videos.",
544
551
  )
552
+ @click.option("--from", "from_user", type=str, default=None, help="Only tweets from this user.")
553
+ @click.option("--to", "to_user", type=str, default=None, help="Only tweets directed at this user.")
554
+ @click.option("--lang", type=str, default=None, help="Filter by language (ISO code, e.g. en, fr, ja).")
555
+ @click.option("--since", type=str, default=None, help="Tweets since date (YYYY-MM-DD).")
556
+ @click.option("--until", type=str, default=None, help="Tweets until date (YYYY-MM-DD).")
557
+ @click.option(
558
+ "--has",
559
+ type=click.Choice(SEARCH_HAS_CHOICES, case_sensitive=False),
560
+ multiple=True,
561
+ help="Require content type (links, images, videos, media). Repeatable.",
562
+ )
563
+ @click.option(
564
+ "--exclude",
565
+ type=click.Choice(SEARCH_EXCLUDE_CHOICES, case_sensitive=False),
566
+ multiple=True,
567
+ help="Exclude content type (retweets, replies, links). Repeatable.",
568
+ )
569
+ @click.option("--min-likes", type=int, default=None, help="Minimum number of likes.")
570
+ @click.option("--min-retweets", type=int, default=None, help="Minimum number of retweets.")
545
571
  @click.option("--max", "-n", "max_count", type=int, default=None, help="Max number of tweets to fetch.")
546
572
  @structured_output_options
547
573
  @click.option("--output", "-o", "output_file", type=str, default=None, help="Save tweets to JSON file.")
548
574
  @click.option("--filter", "do_filter", is_flag=True, help="Enable score-based filtering.")
549
575
  @click.option("--full-text", is_flag=True, help="Show full tweet text in table output.")
550
576
  @click.pass_context
551
- def search(ctx, query, product, max_count, as_json, as_yaml, output_file, do_filter, full_text):
552
- # type: (Any, str, str, int, bool, bool, Optional[str], bool, bool) -> None
553
- """Search tweets by QUERY string."""
577
+ def search(ctx, query, product, from_user, to_user, lang, since, until, has, exclude, min_likes, min_retweets, max_count, as_json, as_yaml, output_file, do_filter, full_text):
578
+ # type: (Any, str, str, Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], tuple, tuple, Optional[int], Optional[int], int, bool, bool, Optional[str], bool, bool) -> None
579
+ """Search tweets by QUERY string with optional advanced filters.
580
+
581
+ QUERY is the search keywords (optional when using advanced filters).
582
+
583
+ Advanced search examples:
584
+
585
+ \b
586
+ twitter search "python" --from elonmusk
587
+ twitter search "AI" --lang en --since 2026-01-01
588
+ twitter search "rust" --has links --min-likes 100
589
+ twitter search --from bbc --exclude retweets
590
+ """
591
+ from .search import build_search_query
592
+
593
+ composed_query = build_search_query(
594
+ query,
595
+ from_user=from_user,
596
+ to_user=to_user,
597
+ lang=lang,
598
+ since=since,
599
+ until=until,
600
+ has=list(has) if has else None,
601
+ exclude=list(exclude) if exclude else None,
602
+ min_likes=min_likes,
603
+ min_retweets=min_retweets,
604
+ )
605
+ if not composed_query:
606
+ raise click.UsageError("Provide a QUERY or at least one advanced filter (e.g. --from, --lang).")
607
+
554
608
  compact = ctx.obj.get("compact", False)
555
609
  config = load_config()
556
610
  def _run():
557
611
  rich_output = use_rich_output(as_json=as_json, as_yaml=as_yaml, compact=compact)
558
612
  client = _get_client_for_output(config, quiet=not rich_output)
559
613
  _fetch_and_display(
560
- lambda count: client.fetch_search(query, count, product),
561
- "'%s' (%s)" % (query, product), "🔍", max_count, as_json, as_yaml, output_file, do_filter, config,
614
+ lambda count: client.fetch_search(composed_query, count, product),
615
+ "'%s' (%s)" % (composed_query, product), "🔍", max_count, as_json, as_yaml, output_file, do_filter, config,
562
616
  compact=compact, full_text=full_text,
563
617
  )
564
618
  _run_guarded(_run)
@@ -656,6 +710,52 @@ def tweet(ctx, tweet_id, max_count, full_text, as_json, as_yaml):
656
710
  console.print()
657
711
 
658
712
 
713
+ @cli.command()
714
+ @click.argument("tweet_id")
715
+ @structured_output_options
716
+ @click.option("--markdown", "-m", "as_markdown", is_flag=True, help="Output article as Markdown.")
717
+ @click.option("--output", "-o", "output_file", type=str, default=None, help="Save article Markdown to file.")
718
+ @click.pass_context
719
+ def article(ctx, tweet_id, as_json, as_yaml, as_markdown, output_file):
720
+ # type: (Any, str, bool, bool, bool, Optional[str]) -> None
721
+ """Fetch a Twitter Article. TWEET_ID is the numeric tweet ID or full URL."""
722
+ compact = ctx.obj.get("compact", False)
723
+ if compact:
724
+ raise click.UsageError("`twitter article` does not support --compact. Use --markdown or --output.")
725
+ if as_markdown and (as_json or as_yaml):
726
+ raise click.UsageError("Use only one of --markdown, --json, or --yaml.")
727
+
728
+ tweet_id = _normalize_tweet_id(tweet_id)
729
+ config = load_config()
730
+ rich_output = use_rich_output(as_json=as_json, as_yaml=as_yaml, compact=False) and not as_markdown
731
+ try:
732
+ client = _get_client_for_output(config, quiet=not rich_output)
733
+ if rich_output:
734
+ console.print("📰 Fetching article %s...\n" % tweet_id)
735
+ start = time.time()
736
+ article_tweet = client.fetch_article(tweet_id)
737
+ elapsed = time.time() - start
738
+ if rich_output:
739
+ console.print("✅ Fetched article in %.1fs\n" % elapsed)
740
+ except RuntimeError as exc:
741
+ _exit_with_error(exc)
742
+
743
+ markdown = article_to_markdown(article_tweet)
744
+ if output_file:
745
+ Path(output_file).write_text(markdown, encoding="utf-8")
746
+ if rich_output:
747
+ console.print("💾 Saved article Markdown to %s\n" % output_file)
748
+
749
+ if as_markdown:
750
+ click.echo(markdown, nl=False)
751
+ return
752
+ if emit_structured(tweet_to_dict(article_tweet), as_json=as_json, as_yaml=as_yaml):
753
+ return
754
+
755
+ print_article(article_tweet, console)
756
+ console.print()
757
+
758
+
659
759
  @cli.command(name="list")
660
760
  @click.argument("list_id")
661
761
  @click.option("--max", "-n", "max_count", type=int, default=None, help="Max tweets to fetch.")
@@ -321,6 +321,45 @@ class TwitterClient:
321
321
  },
322
322
  )
323
323
 
324
+ def fetch_article(self, tweet_id):
325
+ # type: (str) -> Tweet
326
+ """Fetch a Twitter Article by tweet ID."""
327
+ logger.debug("fetch_article: tweet_id=%s", tweet_id)
328
+
329
+ data = self._graphql_get(
330
+ "TweetResultByRestId",
331
+ variables={
332
+ "tweetId": tweet_id,
333
+ "withCommunity": False,
334
+ "includePromotedContent": False,
335
+ "withVoice": False,
336
+ },
337
+ features={
338
+ "longform_notetweets_consumption_enabled": True,
339
+ "responsive_web_twitter_article_tweet_consumption_enabled": True,
340
+ "longform_notetweets_rich_text_read_enabled": True,
341
+ "longform_notetweets_inline_media_enabled": True,
342
+ "articles_preview_enabled": True,
343
+ "responsive_web_graphql_exclude_directive_enabled": True,
344
+ "verified_phone_label_enabled": False,
345
+ },
346
+ field_toggles={
347
+ "withArticleRichContentState": True,
348
+ "withArticlePlainText": True,
349
+ },
350
+ )
351
+
352
+ result = _deep_get(data, "data", "tweetResult", "result")
353
+ if not result:
354
+ raise NotFoundError("Article not found: tweet_id=%s" % tweet_id)
355
+
356
+ tweet = parse_tweet_result(result)
357
+ if tweet is None or (tweet.article_title is None and tweet.article_text is None):
358
+ raise NotFoundError("Tweet %s has no article content" % tweet_id)
359
+
360
+ logger.info("fetch_article: tweet_id=%s", tweet_id)
361
+ return tweet
362
+
324
363
  def fetch_list_timeline(self, list_id, count=20):
325
364
  # type: (str, int) -> List[Tweet]
326
365
  """Fetch tweets from a Twitter List."""
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  from typing import List, Optional
6
6
 
7
7
  from rich.console import Console
8
+ from rich.markdown import Markdown
8
9
  from rich.panel import Panel
9
10
  from rich.table import Table
10
11
 
@@ -150,6 +151,61 @@ def print_tweet_detail(tweet: Tweet, console: Optional[Console] = None) -> None:
150
151
  ))
151
152
 
152
153
 
154
+ def article_to_markdown(tweet: Tweet) -> str:
155
+ """Convert a Twitter Article tweet into a Markdown document."""
156
+ title = tweet.article_title or "Twitter Article"
157
+ lines = [
158
+ "# %s" % title,
159
+ "",
160
+ "- Author: @%s (%s)" % (tweet.author.screen_name, tweet.author.name),
161
+ "- Published: %s" % (tweet.created_at or "unknown"),
162
+ "- URL: https://x.com/%s/status/%s" % (tweet.author.screen_name, tweet.id),
163
+ "- Likes: %s" % format_number(tweet.metrics.likes),
164
+ "- Retweets: %s" % format_number(tweet.metrics.retweets),
165
+ "- Replies: %s" % format_number(tweet.metrics.replies),
166
+ "- Bookmarks: %s" % format_number(tweet.metrics.bookmarks),
167
+ "- Views: %s" % format_number(tweet.metrics.views),
168
+ ]
169
+
170
+ if tweet.article_text:
171
+ lines.extend(["", tweet.article_text.strip()])
172
+
173
+ return "\n".join(lines).strip() + "\n"
174
+
175
+
176
+ def print_article(tweet: Tweet, console: Optional[Console] = None) -> None:
177
+ """Print a Twitter Article with rich formatting."""
178
+ if console is None:
179
+ console = Console()
180
+
181
+ verified = " ✓" if tweet.author.verified else ""
182
+ title = tweet.article_title or "Twitter Article"
183
+ meta_parts = [
184
+ "By @%s%s (%s)" % (tweet.author.screen_name, verified, tweet.author.name),
185
+ "🕐 %s" % tweet.created_at,
186
+ "🔗 x.com/%s/status/%s" % (tweet.author.screen_name, tweet.id),
187
+ "",
188
+ "❤️ %s 🔄 %s 💬 %s 🔖 %s 👁️ %s"
189
+ % (
190
+ format_number(tweet.metrics.likes),
191
+ format_number(tweet.metrics.retweets),
192
+ format_number(tweet.metrics.replies),
193
+ format_number(tweet.metrics.bookmarks),
194
+ format_number(tweet.metrics.views),
195
+ ),
196
+ ]
197
+ console.print(Panel(
198
+ "\n".join(meta_parts),
199
+ title="📰 %s" % title,
200
+ border_style="blue",
201
+ expand=True,
202
+ ))
203
+
204
+ if tweet.article_text:
205
+ console.print()
206
+ console.print(Markdown(tweet.article_text))
207
+
208
+
153
209
  def print_filter_stats(
154
210
  original_count: int,
155
211
  filtered: List[Tweet],
@@ -43,6 +43,7 @@ FALLBACK_QUERY_IDS = {
43
43
  "DeleteRetweet": "iQtK4dl5hBmXewYZuEOKVw",
44
44
  "CreateBookmark": "aoDbu3RHznuiSkQ9aNM67Q",
45
45
  "DeleteBookmark": "Wlmlj2-xISYCixDmuS8KNg",
46
+ "TweetResultByRestId": "7xflPyRiUxGVbJd4uWmbfg",
46
47
  }
47
48
 
48
49
  # ── Default feature flags ────────────────────────────────────────────────
@@ -0,0 +1,79 @@
1
+ """Advanced search query builder.
2
+
3
+ Composes Twitter search operators into a raw query string for the
4
+ SearchTimeline GraphQL endpoint.
5
+
6
+ Reference: https://help.x.com/en/using-x/x-advanced-search
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import List, Optional, Sequence
12
+
13
+
14
+ def build_search_query(
15
+ query: str = "",
16
+ *,
17
+ from_user: Optional[str] = None,
18
+ to_user: Optional[str] = None,
19
+ lang: Optional[str] = None,
20
+ since: Optional[str] = None,
21
+ until: Optional[str] = None,
22
+ has: Optional[Sequence[str]] = None,
23
+ exclude: Optional[Sequence[str]] = None,
24
+ min_likes: Optional[int] = None,
25
+ min_retweets: Optional[int] = None,
26
+ ) -> str:
27
+ """Build an advanced search query string.
28
+
29
+ Args:
30
+ query: Base search keywords.
31
+ from_user: Only tweets from this user (screen_name).
32
+ to_user: Only tweets directed at this user.
33
+ lang: ISO 639-1 language code (e.g. "en", "fr", "ja").
34
+ since: Start date in YYYY-MM-DD format.
35
+ until: End date in YYYY-MM-DD format.
36
+ has: List of content types to require. Accepted values:
37
+ "links", "images", "videos", "media".
38
+ exclude: List of content types to exclude. Accepted values:
39
+ "retweets", "replies", "links".
40
+ min_likes: Minimum number of likes (faves).
41
+ min_retweets: Minimum number of retweets.
42
+
43
+ Returns:
44
+ Composed query string ready for the rawQuery API parameter.
45
+ """
46
+ parts: List[str] = []
47
+
48
+ if query and query.strip():
49
+ parts.append(query.strip())
50
+
51
+ if from_user:
52
+ parts.append("from:%s" % from_user.lstrip("@"))
53
+ if to_user:
54
+ parts.append("to:%s" % to_user.lstrip("@"))
55
+ if lang:
56
+ parts.append("lang:%s" % lang)
57
+ if since:
58
+ parts.append("since:%s" % since)
59
+ if until:
60
+ parts.append("until:%s" % until)
61
+ if has:
62
+ for item in has:
63
+ parts.append("filter:%s" % item)
64
+ if exclude:
65
+ for item in exclude:
66
+ if item == "retweets":
67
+ parts.append("-filter:retweets")
68
+ elif item == "replies":
69
+ parts.append("-filter:replies")
70
+ elif item == "links":
71
+ parts.append("-filter:links")
72
+ else:
73
+ parts.append("-filter:%s" % item)
74
+ if min_likes is not None:
75
+ parts.append("min_faves:%d" % min_likes)
76
+ if min_retweets is not None:
77
+ parts.append("min_retweets:%d" % min_retweets)
78
+
79
+ return " ".join(parts)
@@ -1010,7 +1010,7 @@ wheels = [
1010
1010
 
1011
1011
  [[package]]
1012
1012
  name = "twitter-cli"
1013
- version = "0.6.5"
1013
+ version = "0.6.6"
1014
1014
  source = { editable = "." }
1015
1015
  dependencies = [
1016
1016
  { name = "beautifulsoup4" },
File without changes
File without changes
File without changes
File without changes