twitter-cli 0.8.1__tar.gz → 0.8.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/PKG-INFO +1 -1
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/pyproject.toml +1 -1
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/test_client.py +21 -15
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/test_parser_fixtures.py +6 -9
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/auth.py +8 -2
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/cli.py +8 -2
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/client.py +3 -27
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/constants.py +0 -5
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/formatter.py +8 -3
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/serialization.py +2 -0
- twitter_cli-0.8.2/twitter_cli/timeutil.py +71 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/uv.lock +1 -1
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/.github/ISSUE_TEMPLATE/feature_request.yml +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/.github/workflows/ci.yml +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/.github/workflows/publish-clawhub.yml +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/.github/workflows/publish.yml +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/.gitignore +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/LICENSE +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/README.md +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/SCHEMA.md +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/SKILL.md +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/config.yaml +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/conftest.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/fixtures/followers_page.json +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/fixtures/home_timeline.json +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/fixtures/list_timeline.json +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/fixtures/search_timeline.json +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/fixtures/tweet_detail.json +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/test_auth.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/test_cli.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/test_config.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/test_config_normalization.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/test_filter.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/test_search.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/test_serialization.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/tests/test_smoke.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/__init__.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/cache.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/config.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/exceptions.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/filter.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/graphql.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/models.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/output.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/parser.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.2}/twitter_cli/search.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: twitter-cli
|
|
3
|
-
Version: 0.8.
|
|
3
|
+
Version: 0.8.2
|
|
4
4
|
Summary: A CLI for Twitter/X — feed, bookmarks, and user timeline in terminal
|
|
5
5
|
Project-URL: Homepage, https://github.com/jackwener/twitter-cli
|
|
6
6
|
Project-URL: Repository, https://github.com/jackwener/twitter-cli
|
|
@@ -13,16 +13,22 @@ import pytest
|
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
from twitter_cli.client import (
|
|
16
|
-
FEATURES,
|
|
17
16
|
_best_chrome_target,
|
|
17
|
+
TwitterClient,
|
|
18
|
+
)
|
|
19
|
+
from twitter_cli.exceptions import TwitterAPIError
|
|
20
|
+
from twitter_cli.graphql import (
|
|
21
|
+
FEATURES,
|
|
18
22
|
_build_graphql_url,
|
|
23
|
+
_update_features_from_html,
|
|
24
|
+
)
|
|
25
|
+
from twitter_cli.parser import (
|
|
19
26
|
_deep_get,
|
|
20
27
|
_extract_cursor,
|
|
21
28
|
_extract_media,
|
|
22
29
|
_parse_int,
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
TwitterClient,
|
|
30
|
+
parse_tweet_result,
|
|
31
|
+
parse_user_result,
|
|
26
32
|
)
|
|
27
33
|
|
|
28
34
|
|
|
@@ -339,9 +345,9 @@ class TestPaginationBehavior:
|
|
|
339
345
|
return [MagicMock(id="tweet-1")], None
|
|
340
346
|
|
|
341
347
|
client._graphql_get = _graphql_get
|
|
342
|
-
client._parse_timeline_response = _parse_timeline_response
|
|
343
348
|
|
|
344
|
-
|
|
349
|
+
with patch('twitter_cli.client.parse_timeline_response', side_effect=_parse_timeline_response):
|
|
350
|
+
tweets = client._fetch_timeline("HomeTimeline", 1, lambda data: data)
|
|
345
351
|
|
|
346
352
|
assert [tweet.id for tweet in tweets] == ["tweet-1"]
|
|
347
353
|
|
|
@@ -357,9 +363,9 @@ class TestPaginationBehavior:
|
|
|
357
363
|
return {"page": len(calls)}
|
|
358
364
|
|
|
359
365
|
client._graphql_get = _graphql_get
|
|
360
|
-
client._parse_timeline_response = lambda data, get_instructions: ([], "cursor-same")
|
|
361
366
|
|
|
362
|
-
|
|
367
|
+
with patch('twitter_cli.client.parse_timeline_response', return_value=([], "cursor-same")):
|
|
368
|
+
tweets = client._fetch_timeline("HomeTimeline", 1, lambda data: data)
|
|
363
369
|
|
|
364
370
|
assert tweets == []
|
|
365
371
|
assert calls == [None, "cursor-same"]
|
|
@@ -401,9 +407,9 @@ class TestPaginationBehavior:
|
|
|
401
407
|
]
|
|
402
408
|
|
|
403
409
|
client._graphql_get = _graphql_get
|
|
404
|
-
client._parse_user_result = _parse_user_result
|
|
405
410
|
|
|
406
|
-
|
|
411
|
+
with patch('twitter_cli.client.parse_user_result', side_effect=_parse_user_result):
|
|
412
|
+
users = client._fetch_user_list("Followers", "1", 1, _get_instructions)
|
|
407
413
|
|
|
408
414
|
assert [user.screen_name for user in users] == ["alice"]
|
|
409
415
|
|
|
@@ -453,7 +459,7 @@ class TestParseTweetResult:
|
|
|
453
459
|
client._ct_init_attempted = True
|
|
454
460
|
client._client_transaction = None
|
|
455
461
|
|
|
456
|
-
tweet =
|
|
462
|
+
tweet = parse_tweet_result(copy.deepcopy(self.SAMPLE_TWEET_RESULT))
|
|
457
463
|
assert tweet is not None
|
|
458
464
|
assert tweet.id == "1234567890"
|
|
459
465
|
assert tweet.text == "Hello world! This is a test tweet."
|
|
@@ -475,7 +481,7 @@ class TestParseTweetResult:
|
|
|
475
481
|
client._client_transaction = None
|
|
476
482
|
|
|
477
483
|
result = {"__typename": "TweetTombstone"}
|
|
478
|
-
assert
|
|
484
|
+
assert parse_tweet_result(result) is None
|
|
479
485
|
|
|
480
486
|
@patch("twitter_cli.client._get_cffi_session")
|
|
481
487
|
@patch("twitter_cli.client._gen_ct_headers", return_value={})
|
|
@@ -491,7 +497,7 @@ class TestParseTweetResult:
|
|
|
491
497
|
"__typename": "TweetWithVisibilityResults",
|
|
492
498
|
"tweet": copy.deepcopy(self.SAMPLE_TWEET_RESULT),
|
|
493
499
|
}
|
|
494
|
-
tweet =
|
|
500
|
+
tweet = parse_tweet_result(wrapped)
|
|
495
501
|
assert tweet is not None
|
|
496
502
|
assert tweet.id == "1234567890"
|
|
497
503
|
|
|
@@ -505,7 +511,7 @@ class TestParseTweetResult:
|
|
|
505
511
|
client._ct_init_attempted = True
|
|
506
512
|
client._client_transaction = None
|
|
507
513
|
|
|
508
|
-
assert
|
|
514
|
+
assert parse_tweet_result(self.SAMPLE_TWEET_RESULT, depth=3) is None
|
|
509
515
|
|
|
510
516
|
|
|
511
517
|
# ── TwitterAPIError ──────────────────────────────────────────────────────
|
|
@@ -523,7 +529,7 @@ class TestTwitterAPIError:
|
|
|
523
529
|
|
|
524
530
|
class TestParseUserResult:
|
|
525
531
|
def test_coerces_count_fields_to_int(self):
|
|
526
|
-
user =
|
|
532
|
+
user = parse_user_result(
|
|
527
533
|
{
|
|
528
534
|
"rest_id": "user-1",
|
|
529
535
|
"legacy": {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
-
from twitter_cli.client import TwitterClient
|
|
3
|
+
from twitter_cli.client import TwitterClient
|
|
4
|
+
from twitter_cli.parser import _deep_get, parse_timeline_response
|
|
4
5
|
|
|
5
6
|
|
|
6
7
|
def _make_client() -> TwitterClient:
|
|
@@ -15,10 +16,9 @@ def _make_client() -> TwitterClient:
|
|
|
15
16
|
|
|
16
17
|
|
|
17
18
|
def test_parse_home_timeline_fixture(fixture_loader) -> None:
|
|
18
|
-
client = _make_client()
|
|
19
19
|
payload = fixture_loader("home_timeline.json")
|
|
20
20
|
|
|
21
|
-
tweets, cursor =
|
|
21
|
+
tweets, cursor = parse_timeline_response(
|
|
22
22
|
payload,
|
|
23
23
|
lambda data: _deep_get(data, "data", "home", "home_timeline_urt", "instructions"),
|
|
24
24
|
)
|
|
@@ -34,10 +34,9 @@ def test_parse_home_timeline_fixture(fixture_loader) -> None:
|
|
|
34
34
|
|
|
35
35
|
|
|
36
36
|
def test_parse_tweet_detail_fixture_with_nested_items(fixture_loader) -> None:
|
|
37
|
-
client = _make_client()
|
|
38
37
|
payload = fixture_loader("tweet_detail.json")
|
|
39
38
|
|
|
40
|
-
tweets, cursor =
|
|
39
|
+
tweets, cursor = parse_timeline_response(
|
|
41
40
|
payload,
|
|
42
41
|
lambda data: _deep_get(data, "data", "threaded_conversation_with_injections_v2", "instructions"),
|
|
43
42
|
)
|
|
@@ -47,10 +46,9 @@ def test_parse_tweet_detail_fixture_with_nested_items(fixture_loader) -> None:
|
|
|
47
46
|
|
|
48
47
|
|
|
49
48
|
def test_parse_search_timeline_fixture_with_module_items(fixture_loader) -> None:
|
|
50
|
-
client = _make_client()
|
|
51
49
|
payload = fixture_loader("search_timeline.json")
|
|
52
50
|
|
|
53
|
-
tweets, cursor =
|
|
51
|
+
tweets, cursor = parse_timeline_response(
|
|
54
52
|
payload,
|
|
55
53
|
lambda data: _deep_get(data, "data", "search_by_raw_query", "search_timeline", "timeline", "instructions"),
|
|
56
54
|
)
|
|
@@ -62,10 +60,9 @@ def test_parse_search_timeline_fixture_with_module_items(fixture_loader) -> None
|
|
|
62
60
|
|
|
63
61
|
|
|
64
62
|
def test_parse_list_timeline_fixture_with_visibility_wrapper(fixture_loader) -> None:
|
|
65
|
-
client = _make_client()
|
|
66
63
|
payload = fixture_loader("list_timeline.json")
|
|
67
64
|
|
|
68
|
-
tweets, cursor =
|
|
65
|
+
tweets, cursor = parse_timeline_response(
|
|
69
66
|
payload,
|
|
70
67
|
lambda data: _deep_get(data, "data", "list", "tweets_timeline", "timeline", "instructions"),
|
|
71
68
|
)
|
|
@@ -353,9 +353,15 @@ def iter_cookie_files(browser_name):
|
|
|
353
353
|
if sys.platform == "darwin":
|
|
354
354
|
root = os.path.join(os.path.expanduser("~"), "Library", "Application Support", base_dir)
|
|
355
355
|
elif sys.platform == "win32":
|
|
356
|
-
|
|
356
|
+
if browser_name == "edge":
|
|
357
|
+
root = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Microsoft", "Edge", "User Data")
|
|
358
|
+
else:
|
|
359
|
+
root = os.path.join(os.environ.get("LOCALAPPDATA", ""), base_dir)
|
|
357
360
|
else:
|
|
358
|
-
|
|
361
|
+
if browser_name == "edge":
|
|
362
|
+
root = os.path.join(os.path.expanduser("~"), ".config", "microsoft-edge")
|
|
363
|
+
else:
|
|
364
|
+
root = os.path.join(os.path.expanduser("~"), ".config", base_dir)
|
|
359
365
|
if not os.path.isdir(root):
|
|
360
366
|
return []
|
|
361
367
|
env_profile = os.environ.get("TWITTER_CHROME_PROFILE", "").strip()
|
|
@@ -737,10 +737,11 @@ def _print_show_hint():
|
|
|
737
737
|
@click.argument("index", type=click.IntRange(1))
|
|
738
738
|
@click.option("--max", "-n", "max_count", type=int, default=None, help="Max replies to fetch.")
|
|
739
739
|
@click.option("--full-text", is_flag=True, help="Show full reply text in table output.")
|
|
740
|
+
@click.option("--output", "-o", "output_file", type=str, default=None, help="Save tweet detail as JSON to file.")
|
|
740
741
|
@structured_output_options
|
|
741
742
|
@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
|
|
743
|
+
def show(ctx, index, max_count, full_text, output_file, as_json, as_yaml):
|
|
744
|
+
# type: (Any, int, Optional[int], bool, Optional[str], bool, bool) -> None
|
|
744
745
|
"""View tweet #INDEX from the last feed/search results."""
|
|
745
746
|
compact = ctx.obj.get("compact", False)
|
|
746
747
|
|
|
@@ -769,6 +770,11 @@ def show(ctx, index, max_count, full_text, as_json, as_yaml):
|
|
|
769
770
|
except RuntimeError as exc:
|
|
770
771
|
_exit_with_error(exc)
|
|
771
772
|
|
|
773
|
+
if output_file:
|
|
774
|
+
Path(output_file).write_text(tweets_to_json(tweets), encoding="utf-8")
|
|
775
|
+
if rich_output:
|
|
776
|
+
console.print("💾 Saved to %s\n" % output_file)
|
|
777
|
+
|
|
772
778
|
_emit_tweet_detail(tweets, compact=compact, as_json=as_json, as_yaml=as_yaml, full_text=full_text)
|
|
773
779
|
|
|
774
780
|
|
|
@@ -40,6 +40,7 @@ from .exceptions import (
|
|
|
40
40
|
TwitterAPIError,
|
|
41
41
|
)
|
|
42
42
|
from .graphql import (
|
|
43
|
+
FALLBACK_QUERY_IDS,
|
|
43
44
|
FEATURES,
|
|
44
45
|
_build_graphql_url,
|
|
45
46
|
_invalidate_query_id,
|
|
@@ -715,7 +716,7 @@ class TwitterClient:
|
|
|
715
716
|
variables["cursor"] = cursor
|
|
716
717
|
|
|
717
718
|
data = self._graphql_get(operation_name, variables, FEATURES, field_toggles=field_toggles)
|
|
718
|
-
new_tweets, next_cursor =
|
|
719
|
+
new_tweets, next_cursor = parse_timeline_response(data, get_instructions)
|
|
719
720
|
|
|
720
721
|
for tweet in new_tweets:
|
|
721
722
|
if tweet.id and tweet.id not in seen_ids:
|
|
@@ -780,7 +781,7 @@ class TwitterClient:
|
|
|
780
781
|
item = content.get("itemContent", {})
|
|
781
782
|
user_results = _deep_get(item, "user_results", "result")
|
|
782
783
|
if user_results:
|
|
783
|
-
user =
|
|
784
|
+
user = parse_user_result(user_results)
|
|
784
785
|
if user:
|
|
785
786
|
new_users.append(user)
|
|
786
787
|
elif entry_type == "TimelineTimelineCursor":
|
|
@@ -1081,28 +1082,3 @@ class TwitterClient:
|
|
|
1081
1082
|
except Exception as exc:
|
|
1082
1083
|
logger.debug("Failed to generate transaction id: %s", exc)
|
|
1083
1084
|
return headers
|
|
1084
|
-
|
|
1085
|
-
# ── Backward-compatible delegation to parser module ──────────────
|
|
1086
|
-
|
|
1087
|
-
@staticmethod
|
|
1088
|
-
def _parse_user_result(user_data):
|
|
1089
|
-
# type: (Dict[str, Any]) -> Optional[UserProfile]
|
|
1090
|
-
"""Parse a user result object into UserProfile."""
|
|
1091
|
-
return parse_user_result(user_data)
|
|
1092
|
-
|
|
1093
|
-
def _parse_tweet_result(self, result, depth=0):
|
|
1094
|
-
# type: (Dict[str, Any], int) -> Optional[Tweet]
|
|
1095
|
-
"""Parse a single TweetResult into a Tweet dataclass."""
|
|
1096
|
-
return parse_tweet_result(result, depth)
|
|
1097
|
-
|
|
1098
|
-
def _parse_timeline_response(self, data, get_instructions):
|
|
1099
|
-
# type: (Any, Callable[[Any], Any]) -> Tuple[List[Tweet], Optional[str]]
|
|
1100
|
-
"""Parse timeline GraphQL response into tweets and next cursor."""
|
|
1101
|
-
return parse_timeline_response(data, get_instructions)
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
# ── Backward compatibility re-exports ────────────────────────────────────
|
|
1105
|
-
# These keep existing test imports working without modification.
|
|
1106
|
-
|
|
1107
|
-
from .graphql import FALLBACK_QUERY_IDS # noqa: E402, F401
|
|
1108
|
-
from .parser import _extract_cursor, _extract_media # noqa: E402, F401
|
|
@@ -121,8 +121,3 @@ SEC_CH_UA_ARCH = get_sec_ch_ua_arch()
|
|
|
121
121
|
SEC_CH_UA_BITNESS = '"64"'
|
|
122
122
|
SEC_CH_UA_MODEL = '""'
|
|
123
123
|
SEC_CH_UA_PLATFORM_VERSION = get_sec_ch_ua_platform_version()
|
|
124
|
-
|
|
125
|
-
# Legacy aliases — modules that import these get the default value.
|
|
126
|
-
# _build_headers() should use get_user_agent() / get_sec_ch_ua() instead.
|
|
127
|
-
USER_AGENT = get_user_agent()
|
|
128
|
-
SEC_CH_UA = get_sec_ch_ua()
|
|
@@ -10,6 +10,7 @@ from rich.panel import Panel
|
|
|
10
10
|
from rich.table import Table
|
|
11
11
|
|
|
12
12
|
from .models import Tweet, UserProfile
|
|
13
|
+
from .timeutil import format_local_time, format_relative_time
|
|
13
14
|
|
|
14
15
|
|
|
15
16
|
def format_number(n: int) -> str:
|
|
@@ -77,13 +78,15 @@ def print_tweet_table(
|
|
|
77
78
|
text += "\n🔗 x.com/%s/status/%s" % (tweet.author.screen_name, tweet.id)
|
|
78
79
|
|
|
79
80
|
# Stats
|
|
81
|
+
rel_time = format_relative_time(tweet.created_at)
|
|
80
82
|
stats = (
|
|
81
|
-
"❤️ %s 🔄 %s\n💬 %s 👁️ %s"
|
|
83
|
+
"❤️ %s 🔄 %s\n💬 %s 👁️ %s\n🕐 %s"
|
|
82
84
|
% (
|
|
83
85
|
format_number(tweet.metrics.likes),
|
|
84
86
|
format_number(tweet.metrics.retweets),
|
|
85
87
|
format_number(tweet.metrics.replies),
|
|
86
88
|
format_number(tweet.metrics.views),
|
|
89
|
+
rel_time,
|
|
87
90
|
)
|
|
88
91
|
)
|
|
89
92
|
|
|
@@ -138,9 +141,11 @@ def print_tweet_detail(tweet: Tweet, console: Optional[Console] = None) -> None:
|
|
|
138
141
|
format_number(tweet.metrics.views),
|
|
139
142
|
)
|
|
140
143
|
)
|
|
144
|
+
local_time = format_local_time(tweet.created_at)
|
|
145
|
+
rel_time = format_relative_time(tweet.created_at)
|
|
141
146
|
body_parts.append(
|
|
142
|
-
"🕐 %s · https://x.com/%s/status/%s"
|
|
143
|
-
% (
|
|
147
|
+
"🕐 %s (%s) · https://x.com/%s/status/%s"
|
|
148
|
+
% (local_time, rel_time, tweet.author.screen_name, tweet.id)
|
|
144
149
|
)
|
|
145
150
|
|
|
146
151
|
console.print(Panel(
|
|
@@ -6,6 +6,7 @@ import json
|
|
|
6
6
|
from typing import Any, Dict, Iterable, List, Optional
|
|
7
7
|
|
|
8
8
|
from .models import Author, Metrics, Tweet, TweetMedia, UserProfile
|
|
9
|
+
from .timeutil import format_local_time
|
|
9
10
|
|
|
10
11
|
|
|
11
12
|
def tweet_to_dict(tweet: Tweet) -> Dict[str, Any]:
|
|
@@ -29,6 +30,7 @@ def tweet_to_dict(tweet: Tweet) -> Dict[str, Any]:
|
|
|
29
30
|
"bookmarks": tweet.metrics.bookmarks,
|
|
30
31
|
},
|
|
31
32
|
"createdAt": tweet.created_at,
|
|
33
|
+
"createdAtLocal": format_local_time(tweet.created_at),
|
|
32
34
|
"media": [
|
|
33
35
|
{
|
|
34
36
|
"type": media.type,
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Time formatting utilities for twitter-cli.
|
|
2
|
+
|
|
3
|
+
Converts Twitter API timestamps (e.g. "Sat Mar 08 12:00:00 +0000 2026")
|
|
4
|
+
into human-friendly local time and relative time strings.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
# Twitter API timestamp format: "Sat Mar 08 12:00:00 +0000 2026"
|
|
16
|
+
_TWITTER_TIME_FORMAT = "%a %b %d %H:%M:%S %z %Y"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _parse_twitter_time(created_at: str) -> Optional[datetime]:
|
|
20
|
+
"""Parse a Twitter API timestamp into a timezone-aware datetime."""
|
|
21
|
+
if not created_at:
|
|
22
|
+
return None
|
|
23
|
+
try:
|
|
24
|
+
return datetime.strptime(created_at, _TWITTER_TIME_FORMAT)
|
|
25
|
+
except (ValueError, TypeError):
|
|
26
|
+
logger.debug("Failed to parse Twitter timestamp: %s", created_at)
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def format_local_time(created_at: str) -> str:
|
|
31
|
+
"""Convert Twitter timestamp to local time string.
|
|
32
|
+
|
|
33
|
+
Returns "2026-03-14 21:08" or the original string on parse failure.
|
|
34
|
+
"""
|
|
35
|
+
dt = _parse_twitter_time(created_at)
|
|
36
|
+
if dt is None:
|
|
37
|
+
return created_at
|
|
38
|
+
local_dt = dt.astimezone()
|
|
39
|
+
return local_dt.strftime("%Y-%m-%d %H:%M")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def format_relative_time(created_at: str) -> str:
|
|
43
|
+
"""Convert Twitter timestamp to a relative time string.
|
|
44
|
+
|
|
45
|
+
Returns e.g. "2m ago", "3h ago", "5d ago", or the original string on failure.
|
|
46
|
+
"""
|
|
47
|
+
dt = _parse_twitter_time(created_at)
|
|
48
|
+
if dt is None:
|
|
49
|
+
return created_at
|
|
50
|
+
now = datetime.now(timezone.utc)
|
|
51
|
+
delta = now - dt
|
|
52
|
+
seconds = int(delta.total_seconds())
|
|
53
|
+
|
|
54
|
+
if seconds < 0:
|
|
55
|
+
return "just now"
|
|
56
|
+
if seconds < 60:
|
|
57
|
+
return "%ds ago" % seconds
|
|
58
|
+
minutes = seconds // 60
|
|
59
|
+
if minutes < 60:
|
|
60
|
+
return "%dm ago" % minutes
|
|
61
|
+
hours = minutes // 60
|
|
62
|
+
if hours < 24:
|
|
63
|
+
return "%dh ago" % hours
|
|
64
|
+
days = hours // 24
|
|
65
|
+
if days < 30:
|
|
66
|
+
return "%dd ago" % days
|
|
67
|
+
months = days // 30
|
|
68
|
+
if months < 12:
|
|
69
|
+
return "%dmo ago" % months
|
|
70
|
+
years = days // 365
|
|
71
|
+
return "%dy ago" % years
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|