twitter-cli 0.6.6__tar.gz → 0.7.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.6.6 → twitter_cli-0.7.1}/.github/workflows/ci.yml +4 -1
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/PKG-INFO +7 -4
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/README.md +5 -2
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/pyproject.toml +3 -3
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/test_cli.py +102 -0
- twitter_cli-0.7.1/tests/test_search.py +113 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/test_serialization.py +15 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/twitter_cli/cli.py +59 -6
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/twitter_cli/client.py +6 -1
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/twitter_cli/graphql.py +4 -1
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/twitter_cli/parser.py +4 -0
- twitter_cli-0.7.1/twitter_cli/search.py +128 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/twitter_cli/serialization.py +2 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/uv.lock +24 -463
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/.github/ISSUE_TEMPLATE/feature_request.yml +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/.github/workflows/publish-clawhub.yml +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/.github/workflows/publish.yml +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/.gitignore +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/LICENSE +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/SCHEMA.md +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/SKILL.md +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/config.yaml +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/conftest.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/fixtures/followers_page.json +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/fixtures/home_timeline.json +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/fixtures/list_timeline.json +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/fixtures/search_timeline.json +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/fixtures/tweet_detail.json +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/test_auth.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/test_client.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/test_config.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/test_config_normalization.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/test_filter.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/test_parser_fixtures.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/tests/test_smoke.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/twitter_cli/__init__.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/twitter_cli/auth.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/twitter_cli/config.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/twitter_cli/constants.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/twitter_cli/exceptions.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/twitter_cli/filter.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/twitter_cli/formatter.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/twitter_cli/models.py +0 -0
- {twitter_cli-0.6.6 → twitter_cli-0.7.1}/twitter_cli/output.py +0 -0
|
@@ -11,7 +11,7 @@ jobs:
|
|
|
11
11
|
runs-on: ubuntu-latest
|
|
12
12
|
strategy:
|
|
13
13
|
matrix:
|
|
14
|
-
python-version: ["3.
|
|
14
|
+
python-version: ["3.10", "3.11", "3.12"]
|
|
15
15
|
steps:
|
|
16
16
|
- name: Checkout
|
|
17
17
|
uses: actions/checkout@v4
|
|
@@ -30,5 +30,8 @@ jobs:
|
|
|
30
30
|
- name: Lint
|
|
31
31
|
run: uv run ruff check .
|
|
32
32
|
|
|
33
|
+
- name: Type check
|
|
34
|
+
run: uv run mypy twitter_cli
|
|
35
|
+
|
|
33
36
|
- name: Test
|
|
34
37
|
run: uv run pytest -q
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: twitter-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.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
|
|
@@ -15,7 +15,7 @@ Classifier: Intended Audience :: Developers
|
|
|
15
15
|
Classifier: License :: OSI Approved :: Apache Software License
|
|
16
16
|
Classifier: Programming Language :: Python :: 3
|
|
17
17
|
Classifier: Topic :: Utilities
|
|
18
|
-
Requires-Python: >=3.
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
19
|
Requires-Dist: beautifulsoup4>=4.12
|
|
20
20
|
Requires-Dist: browser-cookie3>=0.19
|
|
21
21
|
Requires-Dist: click>=8.0
|
|
@@ -34,7 +34,7 @@ Description-Content-Type: text/markdown
|
|
|
34
34
|
|
|
35
35
|
[](https://github.com/jackwener/twitter-cli/actions/workflows/ci.yml)
|
|
36
36
|
[](https://pypi.org/project/twitter-cli/)
|
|
37
|
-
[](https://pypi.org/project/twitter-cli/)
|
|
38
38
|
|
|
39
39
|
A terminal-first CLI for Twitter/X: read timelines, bookmarks, and user profiles without API keys.
|
|
40
40
|
|
|
@@ -129,8 +129,9 @@ twitter feed --filter
|
|
|
129
129
|
# Feed
|
|
130
130
|
twitter feed --max 50
|
|
131
131
|
twitter feed --full-text
|
|
132
|
-
twitter feed --
|
|
132
|
+
twitter feed --output tweets.json
|
|
133
133
|
twitter feed --input tweets.json
|
|
134
|
+
twitter feed --json # Structured stdout for scripts/agents
|
|
134
135
|
|
|
135
136
|
# Bookmarks
|
|
136
137
|
twitter bookmarks
|
|
@@ -142,6 +143,8 @@ twitter search "Claude Code"
|
|
|
142
143
|
twitter search "AI agent" -t Latest --max 50
|
|
143
144
|
twitter search "AI agent" --full-text
|
|
144
145
|
twitter search "机器学习" --yaml
|
|
146
|
+
twitter search "python" --from elonmusk --lang en --since 2026-01-01
|
|
147
|
+
twitter search --from bbc --exclude retweets --has links
|
|
145
148
|
twitter search "topic" -o results.json # Save to file
|
|
146
149
|
twitter search "trending" --filter # Apply ranking filter
|
|
147
150
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://github.com/jackwener/twitter-cli/actions/workflows/ci.yml)
|
|
4
4
|
[](https://pypi.org/project/twitter-cli/)
|
|
5
|
-
[](https://pypi.org/project/twitter-cli/)
|
|
6
6
|
|
|
7
7
|
A terminal-first CLI for Twitter/X: read timelines, bookmarks, and user profiles without API keys.
|
|
8
8
|
|
|
@@ -97,8 +97,9 @@ twitter feed --filter
|
|
|
97
97
|
# Feed
|
|
98
98
|
twitter feed --max 50
|
|
99
99
|
twitter feed --full-text
|
|
100
|
-
twitter feed --
|
|
100
|
+
twitter feed --output tweets.json
|
|
101
101
|
twitter feed --input tweets.json
|
|
102
|
+
twitter feed --json # Structured stdout for scripts/agents
|
|
102
103
|
|
|
103
104
|
# Bookmarks
|
|
104
105
|
twitter bookmarks
|
|
@@ -110,6 +111,8 @@ twitter search "Claude Code"
|
|
|
110
111
|
twitter search "AI agent" -t Latest --max 50
|
|
111
112
|
twitter search "AI agent" --full-text
|
|
112
113
|
twitter search "机器学习" --yaml
|
|
114
|
+
twitter search "python" --from elonmusk --lang en --since 2026-01-01
|
|
115
|
+
twitter search --from bbc --exclude retweets --has links
|
|
113
116
|
twitter search "topic" -o results.json # Save to file
|
|
114
117
|
twitter search "trending" --filter # Apply ranking filter
|
|
115
118
|
|
|
@@ -4,11 +4,11 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "twitter-cli"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.7.1"
|
|
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"
|
|
11
|
-
requires-python = ">=3.
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
12
|
authors = [{ name = "jackwener", email = "jakevingoo@gmail.com" }]
|
|
13
13
|
keywords = ["twitter", "x", "cli", "feed", "timeline"]
|
|
14
14
|
classifiers = [
|
|
@@ -57,7 +57,7 @@ markers = [
|
|
|
57
57
|
line-length = 100
|
|
58
58
|
|
|
59
59
|
[tool.mypy]
|
|
60
|
-
python_version = "3.
|
|
60
|
+
python_version = "3.10"
|
|
61
61
|
ignore_missing_imports = true
|
|
62
62
|
check_untyped_defs = true
|
|
63
63
|
warn_unused_ignores = true
|
|
@@ -44,6 +44,26 @@ def test_cli_feed_json_input_path(tmp_path, tweet_factory) -> None:
|
|
|
44
44
|
assert '"id": "1"' in result.output
|
|
45
45
|
|
|
46
46
|
|
|
47
|
+
def test_cli_feed_input_accepts_structured_json_envelope(tmp_path, tweet_factory) -> None:
|
|
48
|
+
json_path = tmp_path / "tweets.json"
|
|
49
|
+
json_path.write_text(
|
|
50
|
+
(
|
|
51
|
+
"{\n"
|
|
52
|
+
' "ok": true,\n'
|
|
53
|
+
' "schema_version": "1",\n'
|
|
54
|
+
' "data": %s\n'
|
|
55
|
+
"}\n"
|
|
56
|
+
)
|
|
57
|
+
% tweets_to_json([tweet_factory("1")]),
|
|
58
|
+
encoding="utf-8",
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
runner = CliRunner()
|
|
62
|
+
result = runner.invoke(cli, ["feed", "--input", str(json_path), "--json"])
|
|
63
|
+
assert result.exit_code == 0
|
|
64
|
+
assert '"id": "1"' in result.output
|
|
65
|
+
|
|
66
|
+
|
|
47
67
|
def test_print_tweet_table_truncates_text_by_default(tweet_factory) -> None:
|
|
48
68
|
long_text = "A" * 140
|
|
49
69
|
console = Console(record=True, width=400)
|
|
@@ -425,6 +445,88 @@ def test_cli_unfollow_command(monkeypatch) -> None:
|
|
|
425
445
|
assert actions == [("unfollow", "42")]
|
|
426
446
|
|
|
427
447
|
|
|
448
|
+
def test_cli_search_advanced_options(monkeypatch) -> None:
|
|
449
|
+
captured = {}
|
|
450
|
+
|
|
451
|
+
class FakeClient:
|
|
452
|
+
def fetch_search(self, query: str, count: int, product: str):
|
|
453
|
+
captured["query"] = query
|
|
454
|
+
captured["product"] = product
|
|
455
|
+
return []
|
|
456
|
+
|
|
457
|
+
monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None: FakeClient())
|
|
458
|
+
monkeypatch.setattr(
|
|
459
|
+
"twitter_cli.cli.load_config",
|
|
460
|
+
lambda: {"fetch": {"count": 50}, "filter": {}, "rateLimit": {}},
|
|
461
|
+
)
|
|
462
|
+
runner = CliRunner()
|
|
463
|
+
|
|
464
|
+
result = runner.invoke(cli, [
|
|
465
|
+
"search", "python",
|
|
466
|
+
"--from", "elonmusk",
|
|
467
|
+
"--lang", "en",
|
|
468
|
+
"--since", "2026-01-01",
|
|
469
|
+
"--has", "links",
|
|
470
|
+
"--exclude", "retweets",
|
|
471
|
+
"--min-likes", "100",
|
|
472
|
+
"-t", "Latest",
|
|
473
|
+
"--json",
|
|
474
|
+
])
|
|
475
|
+
|
|
476
|
+
assert result.exit_code == 0, f"search failed: {result.output}"
|
|
477
|
+
assert captured["query"] == (
|
|
478
|
+
"python from:elonmusk lang:en since:2026-01-01 "
|
|
479
|
+
"filter:links -filter:retweets min_faves:100"
|
|
480
|
+
)
|
|
481
|
+
assert captured["product"] == "Latest"
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def test_cli_search_operators_only_no_query(monkeypatch) -> None:
|
|
485
|
+
captured = {}
|
|
486
|
+
|
|
487
|
+
class FakeClient:
|
|
488
|
+
def fetch_search(self, query: str, count: int, product: str):
|
|
489
|
+
captured["query"] = query
|
|
490
|
+
return []
|
|
491
|
+
|
|
492
|
+
monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None: FakeClient())
|
|
493
|
+
monkeypatch.setattr(
|
|
494
|
+
"twitter_cli.cli.load_config",
|
|
495
|
+
lambda: {"fetch": {"count": 50}, "filter": {}, "rateLimit": {}},
|
|
496
|
+
)
|
|
497
|
+
runner = CliRunner()
|
|
498
|
+
|
|
499
|
+
result = runner.invoke(cli, ["search", "--from", "bbc", "--json"])
|
|
500
|
+
assert result.exit_code == 0, f"search failed: {result.output}"
|
|
501
|
+
assert captured["query"] == "from:bbc"
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def test_cli_search_empty_query_no_options() -> None:
|
|
505
|
+
runner = CliRunner()
|
|
506
|
+
|
|
507
|
+
result = runner.invoke(cli, ["search"])
|
|
508
|
+
assert result.exit_code != 0
|
|
509
|
+
assert "Provide a QUERY" in result.output
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def test_cli_search_invalid_date_rejected(monkeypatch) -> None:
|
|
513
|
+
monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None: None)
|
|
514
|
+
runner = CliRunner()
|
|
515
|
+
|
|
516
|
+
result = runner.invoke(cli, ["search", "python", "--since", "not-a-date"])
|
|
517
|
+
assert result.exit_code != 0
|
|
518
|
+
assert "--since must be in YYYY-MM-DD format" in result.output
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def test_cli_search_rejects_reversed_date_range(monkeypatch) -> None:
|
|
522
|
+
monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None: None)
|
|
523
|
+
runner = CliRunner()
|
|
524
|
+
|
|
525
|
+
result = runner.invoke(cli, ["search", "python", "--since", "2026-03-02", "--until", "2026-03-01"])
|
|
526
|
+
assert result.exit_code != 0
|
|
527
|
+
assert "--since must be on or before --until" in result.output
|
|
528
|
+
|
|
529
|
+
|
|
428
530
|
def test_cli_compact_mode(tmp_path, tweet_factory) -> None:
|
|
429
531
|
json_path = tmp_path / "tweets.json"
|
|
430
532
|
json_path.write_text(tweets_to_json([tweet_factory("1")]), encoding="utf-8")
|
|
@@ -0,0 +1,113 @@
|
|
|
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_lang_is_trimmed_and_lowercased(self) -> None:
|
|
28
|
+
assert build_search_query("news", lang=" EN ") == "news lang:en"
|
|
29
|
+
|
|
30
|
+
def test_since(self) -> None:
|
|
31
|
+
assert build_search_query("python", since="2026-01-01") == "python since:2026-01-01"
|
|
32
|
+
|
|
33
|
+
def test_until(self) -> None:
|
|
34
|
+
assert build_search_query("python", until="2026-03-01") == "python until:2026-03-01"
|
|
35
|
+
|
|
36
|
+
def test_date_range(self) -> None:
|
|
37
|
+
result = build_search_query("rust", since="2026-01-01", until="2026-03-01")
|
|
38
|
+
assert result == "rust since:2026-01-01 until:2026-03-01"
|
|
39
|
+
|
|
40
|
+
def test_has_links(self) -> None:
|
|
41
|
+
assert build_search_query("python", has=["links"]) == "python filter:links"
|
|
42
|
+
|
|
43
|
+
def test_has_multiple(self) -> None:
|
|
44
|
+
result = build_search_query("art", has=["images", "videos"])
|
|
45
|
+
assert result == "art filter:images filter:videos"
|
|
46
|
+
|
|
47
|
+
def test_exclude_retweets(self) -> None:
|
|
48
|
+
assert build_search_query("news", exclude=["retweets"]) == "news -filter:retweets"
|
|
49
|
+
|
|
50
|
+
def test_exclude_replies(self) -> None:
|
|
51
|
+
assert build_search_query("news", exclude=["replies"]) == "news -filter:replies"
|
|
52
|
+
|
|
53
|
+
def test_exclude_multiple(self) -> None:
|
|
54
|
+
result = build_search_query("news", exclude=["retweets", "replies"])
|
|
55
|
+
assert result == "news -filter:retweets -filter:replies"
|
|
56
|
+
|
|
57
|
+
def test_min_likes(self) -> None:
|
|
58
|
+
assert build_search_query("python", min_likes=100) == "python min_faves:100"
|
|
59
|
+
|
|
60
|
+
def test_min_retweets(self) -> None:
|
|
61
|
+
assert build_search_query("python", min_retweets=50) == "python min_retweets:50"
|
|
62
|
+
|
|
63
|
+
def test_combined_operators(self) -> None:
|
|
64
|
+
result = build_search_query(
|
|
65
|
+
"machine learning",
|
|
66
|
+
from_user="openai",
|
|
67
|
+
lang="en",
|
|
68
|
+
since="2026-01-01",
|
|
69
|
+
has=["links"],
|
|
70
|
+
min_likes=50,
|
|
71
|
+
exclude=["retweets"],
|
|
72
|
+
)
|
|
73
|
+
assert result == (
|
|
74
|
+
"machine learning from:openai lang:en since:2026-01-01 "
|
|
75
|
+
"filter:links -filter:retweets min_faves:50"
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
def test_operators_only_no_query(self) -> None:
|
|
79
|
+
result = build_search_query("", from_user="elonmusk", since="2026-03-01")
|
|
80
|
+
assert result == "from:elonmusk since:2026-03-01"
|
|
81
|
+
|
|
82
|
+
def test_date_range_rejects_reversed_order(self) -> None:
|
|
83
|
+
try:
|
|
84
|
+
build_search_query("python", since="2026-03-02", until="2026-03-01")
|
|
85
|
+
except ValueError as exc:
|
|
86
|
+
assert "--since must be on or before --until" in str(exc)
|
|
87
|
+
else:
|
|
88
|
+
raise AssertionError("Expected ValueError for reversed date range")
|
|
89
|
+
|
|
90
|
+
def test_invalid_since_rejected(self) -> None:
|
|
91
|
+
try:
|
|
92
|
+
build_search_query("python", since="not-a-date")
|
|
93
|
+
except ValueError as exc:
|
|
94
|
+
assert "--since must be in YYYY-MM-DD format" in str(exc)
|
|
95
|
+
else:
|
|
96
|
+
raise AssertionError("Expected ValueError for invalid since date")
|
|
97
|
+
|
|
98
|
+
def test_negative_min_likes_rejected(self) -> None:
|
|
99
|
+
try:
|
|
100
|
+
build_search_query("python", min_likes=-1)
|
|
101
|
+
except ValueError as exc:
|
|
102
|
+
assert "--min-likes must be greater than or equal to 0" in str(exc)
|
|
103
|
+
else:
|
|
104
|
+
raise AssertionError("Expected ValueError for negative min_likes")
|
|
105
|
+
|
|
106
|
+
def test_whitespace_query_trimmed(self) -> None:
|
|
107
|
+
assert build_search_query(" python ", lang="en") == "python lang:en"
|
|
108
|
+
|
|
109
|
+
def test_empty_has_list(self) -> None:
|
|
110
|
+
assert build_search_query("test", has=[]) == "test"
|
|
111
|
+
|
|
112
|
+
def test_empty_exclude_list(self) -> None:
|
|
113
|
+
assert build_search_query("test", exclude=[]) == "test"
|
|
@@ -22,6 +22,21 @@ def test_tweets_json_roundtrip(tweet_factory) -> None:
|
|
|
22
22
|
assert restored[1].lang == "zh"
|
|
23
23
|
|
|
24
24
|
|
|
25
|
+
def test_tweets_from_json_accepts_structured_success_envelope(tweet_factory) -> None:
|
|
26
|
+
tweets = [tweet_factory("1")]
|
|
27
|
+
raw = (
|
|
28
|
+
"{\n"
|
|
29
|
+
' "ok": true,\n'
|
|
30
|
+
' "schema_version": "1",\n'
|
|
31
|
+
' "data": %s\n'
|
|
32
|
+
"}\n"
|
|
33
|
+
) % tweets_to_json(tweets)
|
|
34
|
+
|
|
35
|
+
restored = tweets_from_json(raw)
|
|
36
|
+
|
|
37
|
+
assert [tweet.id for tweet in restored] == ["1"]
|
|
38
|
+
|
|
39
|
+
|
|
25
40
|
def test_compact_serialization(tweet_factory) -> None:
|
|
26
41
|
from twitter_cli.serialization import tweet_to_compact_dict, tweets_to_compact_json
|
|
27
42
|
import json
|
|
@@ -5,6 +5,7 @@ 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
|
|
@@ -87,6 +88,8 @@ logger = logging.getLogger(__name__)
|
|
|
87
88
|
console = Console(stderr=True)
|
|
88
89
|
FEED_TYPES = ["for-you", "following"]
|
|
89
90
|
SEARCH_PRODUCTS = ["Top", "Latest", "Photos", "Videos"]
|
|
91
|
+
SEARCH_HAS_CHOICES = ["links", "images", "videos", "media"]
|
|
92
|
+
SEARCH_EXCLUDE_CHOICES = ["retweets", "replies", "links"]
|
|
90
93
|
|
|
91
94
|
|
|
92
95
|
def _agent_user_profile(profile: UserProfile) -> dict:
|
|
@@ -537,7 +540,7 @@ def user_posts(ctx, screen_name, max_count, as_json, as_yaml, output_file, full_
|
|
|
537
540
|
|
|
538
541
|
|
|
539
542
|
@cli.command()
|
|
540
|
-
@click.argument("query")
|
|
543
|
+
@click.argument("query", default="")
|
|
541
544
|
@click.option(
|
|
542
545
|
"--type",
|
|
543
546
|
"-t",
|
|
@@ -546,23 +549,73 @@ def user_posts(ctx, screen_name, max_count, as_json, as_yaml, output_file, full_
|
|
|
546
549
|
default="Top",
|
|
547
550
|
help="Search tab: Top, Latest, Photos, or Videos.",
|
|
548
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=click.IntRange(min=0), default=None, help="Minimum number of likes.")
|
|
570
|
+
@click.option("--min-retweets", type=click.IntRange(min=0), default=None, help="Minimum number of retweets.")
|
|
549
571
|
@click.option("--max", "-n", "max_count", type=int, default=None, help="Max number of tweets to fetch.")
|
|
550
572
|
@structured_output_options
|
|
551
573
|
@click.option("--output", "-o", "output_file", type=str, default=None, help="Save tweets to JSON file.")
|
|
552
574
|
@click.option("--filter", "do_filter", is_flag=True, help="Enable score-based filtering.")
|
|
553
575
|
@click.option("--full-text", is_flag=True, help="Show full tweet text in table output.")
|
|
554
576
|
@click.pass_context
|
|
555
|
-
def search(ctx, query, product, max_count, as_json, as_yaml, output_file, do_filter, full_text):
|
|
556
|
-
# type: (Any, str, str, int, bool, bool, Optional[str], bool, bool) -> None
|
|
557
|
-
"""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
|
+
try:
|
|
594
|
+
composed_query = build_search_query(
|
|
595
|
+
query,
|
|
596
|
+
from_user=from_user,
|
|
597
|
+
to_user=to_user,
|
|
598
|
+
lang=lang,
|
|
599
|
+
since=since,
|
|
600
|
+
until=until,
|
|
601
|
+
has=list(has) if has else None,
|
|
602
|
+
exclude=list(exclude) if exclude else None,
|
|
603
|
+
min_likes=min_likes,
|
|
604
|
+
min_retweets=min_retweets,
|
|
605
|
+
)
|
|
606
|
+
except ValueError as exc:
|
|
607
|
+
raise click.UsageError(str(exc)) from exc
|
|
608
|
+
if not composed_query:
|
|
609
|
+
raise click.UsageError("Provide a QUERY or at least one advanced filter (e.g. --from, --lang).")
|
|
610
|
+
|
|
558
611
|
compact = ctx.obj.get("compact", False)
|
|
559
612
|
config = load_config()
|
|
560
613
|
def _run():
|
|
561
614
|
rich_output = use_rich_output(as_json=as_json, as_yaml=as_yaml, compact=compact)
|
|
562
615
|
client = _get_client_for_output(config, quiet=not rich_output)
|
|
563
616
|
_fetch_and_display(
|
|
564
|
-
lambda count: client.fetch_search(
|
|
565
|
-
"'%s' (%s)" % (
|
|
617
|
+
lambda count: client.fetch_search(composed_query, count, product),
|
|
618
|
+
"'%s' (%s)" % (composed_query, product), "🔍", max_count, as_json, as_yaml, output_file, do_filter, config,
|
|
566
619
|
compact=compact, full_text=full_text,
|
|
567
620
|
)
|
|
568
621
|
_run_guarded(_run)
|
|
@@ -9,7 +9,7 @@ import os
|
|
|
9
9
|
import random
|
|
10
10
|
import time
|
|
11
11
|
import urllib.parse
|
|
12
|
-
from typing import Any, Callable,
|
|
12
|
+
from typing import TYPE_CHECKING, Any, Callable, cast
|
|
13
13
|
|
|
14
14
|
import bs4
|
|
15
15
|
from curl_cffi import requests as _cffi_requests
|
|
@@ -52,6 +52,11 @@ from .parser import (
|
|
|
52
52
|
parse_user_result,
|
|
53
53
|
)
|
|
54
54
|
|
|
55
|
+
if TYPE_CHECKING:
|
|
56
|
+
from typing import Dict, List, Optional, Set, Tuple # noqa: F401
|
|
57
|
+
|
|
58
|
+
from .models import Tweet # noqa: F401
|
|
59
|
+
|
|
55
60
|
logger = logging.getLogger(__name__)
|
|
56
61
|
|
|
57
62
|
# Shared curl_cffi session (single-threaded CLI)
|
|
@@ -10,7 +10,10 @@ import json
|
|
|
10
10
|
import logging
|
|
11
11
|
import re
|
|
12
12
|
import urllib.parse
|
|
13
|
-
from typing import
|
|
13
|
+
from typing import TYPE_CHECKING
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from typing import Any, Dict, Optional # noqa: F401
|
|
14
17
|
|
|
15
18
|
from .exceptions import QueryIdError
|
|
16
19
|
|
|
@@ -7,6 +7,10 @@ Converts raw GraphQL response JSON into domain model objects
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
9
|
import logging
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple # noqa: F401
|
|
10
14
|
|
|
11
15
|
from .models import Author, Metrics, Tweet, TweetMedia, UserProfile
|
|
12
16
|
|
|
@@ -0,0 +1,128 @@
|
|
|
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
|
+
import re
|
|
12
|
+
from datetime import date
|
|
13
|
+
from typing import List, Optional, Sequence
|
|
14
|
+
|
|
15
|
+
_LANG_PATTERN = re.compile(r"^[A-Za-z][A-Za-z-]{1,14}$")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _normalize_handle(value: Optional[str]) -> Optional[str]:
|
|
19
|
+
if value is None:
|
|
20
|
+
return None
|
|
21
|
+
text = value.strip().lstrip("@")
|
|
22
|
+
return text or None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _normalize_lang(value: Optional[str]) -> Optional[str]:
|
|
26
|
+
if value is None:
|
|
27
|
+
return None
|
|
28
|
+
text = value.strip().lower()
|
|
29
|
+
if not text:
|
|
30
|
+
return None
|
|
31
|
+
if not _LANG_PATTERN.match(text):
|
|
32
|
+
raise ValueError("--lang must be an ISO language code like en or zh-cn")
|
|
33
|
+
return text
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _normalize_date(flag_name: str, value: Optional[str]) -> Optional[str]:
|
|
37
|
+
if value is None:
|
|
38
|
+
return None
|
|
39
|
+
text = value.strip()
|
|
40
|
+
if not text:
|
|
41
|
+
return None
|
|
42
|
+
try:
|
|
43
|
+
date.fromisoformat(text)
|
|
44
|
+
except ValueError as exc:
|
|
45
|
+
raise ValueError("%s must be in YYYY-MM-DD format" % flag_name) from exc
|
|
46
|
+
return text
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def build_search_query(
|
|
50
|
+
query: str = "",
|
|
51
|
+
*,
|
|
52
|
+
from_user: Optional[str] = None,
|
|
53
|
+
to_user: Optional[str] = None,
|
|
54
|
+
lang: Optional[str] = None,
|
|
55
|
+
since: Optional[str] = None,
|
|
56
|
+
until: Optional[str] = None,
|
|
57
|
+
has: Optional[Sequence[str]] = None,
|
|
58
|
+
exclude: Optional[Sequence[str]] = None,
|
|
59
|
+
min_likes: Optional[int] = None,
|
|
60
|
+
min_retweets: Optional[int] = None,
|
|
61
|
+
) -> str:
|
|
62
|
+
"""Build an advanced search query string.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
query: Base search keywords.
|
|
66
|
+
from_user: Only tweets from this user (screen_name).
|
|
67
|
+
to_user: Only tweets directed at this user.
|
|
68
|
+
lang: ISO 639-1 language code (e.g. "en", "fr", "ja").
|
|
69
|
+
since: Start date in YYYY-MM-DD format.
|
|
70
|
+
until: End date in YYYY-MM-DD format.
|
|
71
|
+
has: List of content types to require. Accepted values:
|
|
72
|
+
"links", "images", "videos", "media".
|
|
73
|
+
exclude: List of content types to exclude. Accepted values:
|
|
74
|
+
"retweets", "replies", "links".
|
|
75
|
+
min_likes: Minimum number of likes (faves).
|
|
76
|
+
min_retweets: Minimum number of retweets.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
Composed query string ready for the rawQuery API parameter.
|
|
80
|
+
"""
|
|
81
|
+
parts: List[str] = []
|
|
82
|
+
query_text = query.strip()
|
|
83
|
+
from_user = _normalize_handle(from_user)
|
|
84
|
+
to_user = _normalize_handle(to_user)
|
|
85
|
+
lang = _normalize_lang(lang)
|
|
86
|
+
since = _normalize_date("--since", since)
|
|
87
|
+
until = _normalize_date("--until", until)
|
|
88
|
+
|
|
89
|
+
if min_likes is not None and min_likes < 0:
|
|
90
|
+
raise ValueError("--min-likes must be greater than or equal to 0")
|
|
91
|
+
if min_retweets is not None and min_retweets < 0:
|
|
92
|
+
raise ValueError("--min-retweets must be greater than or equal to 0")
|
|
93
|
+
if since and until and since > until:
|
|
94
|
+
raise ValueError("--since must be on or before --until")
|
|
95
|
+
|
|
96
|
+
if query_text:
|
|
97
|
+
parts.append(query_text)
|
|
98
|
+
|
|
99
|
+
if from_user:
|
|
100
|
+
parts.append("from:%s" % from_user)
|
|
101
|
+
if to_user:
|
|
102
|
+
parts.append("to:%s" % to_user)
|
|
103
|
+
if lang:
|
|
104
|
+
parts.append("lang:%s" % lang)
|
|
105
|
+
if since:
|
|
106
|
+
parts.append("since:%s" % since)
|
|
107
|
+
if until:
|
|
108
|
+
parts.append("until:%s" % until)
|
|
109
|
+
if has:
|
|
110
|
+
for item in has:
|
|
111
|
+
parts.append("filter:%s" % item.lower())
|
|
112
|
+
if exclude:
|
|
113
|
+
for item in exclude:
|
|
114
|
+
item = item.lower()
|
|
115
|
+
if item == "retweets":
|
|
116
|
+
parts.append("-filter:retweets")
|
|
117
|
+
elif item == "replies":
|
|
118
|
+
parts.append("-filter:replies")
|
|
119
|
+
elif item == "links":
|
|
120
|
+
parts.append("-filter:links")
|
|
121
|
+
else:
|
|
122
|
+
parts.append("-filter:%s" % item)
|
|
123
|
+
if min_likes is not None:
|
|
124
|
+
parts.append("min_faves:%d" % min_likes)
|
|
125
|
+
if min_retweets is not None:
|
|
126
|
+
parts.append("min_retweets:%d" % min_retweets)
|
|
127
|
+
|
|
128
|
+
return " ".join(parts)
|
|
@@ -125,6 +125,8 @@ def tweet_from_dict(data: Dict[str, Any]) -> Tweet:
|
|
|
125
125
|
def tweets_from_json(raw: str) -> List[Tweet]:
|
|
126
126
|
"""Parse a JSON string into Tweet objects."""
|
|
127
127
|
payload = json.loads(raw)
|
|
128
|
+
if isinstance(payload, dict) and payload.get("ok") is True and isinstance(payload.get("data"), list):
|
|
129
|
+
payload = payload["data"]
|
|
128
130
|
if not isinstance(payload, list):
|
|
129
131
|
raise ValueError("Tweet JSON payload must be a list")
|
|
130
132
|
return [tweet_from_dict(item) for item in payload if isinstance(item, dict)]
|