twitter-cli 0.8.1__tar.gz → 0.8.3__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.3}/.github/ISSUE_TEMPLATE/bug_report.yml +1 -1
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/PKG-INFO +30 -26
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/README.md +29 -25
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/pyproject.toml +1 -1
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/fixtures/home_timeline.json +7 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/test_auth.py +1 -1
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/test_client.py +21 -15
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/test_parser_fixtures.py +9 -9
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/auth.py +9 -3
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/cli.py +8 -132
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/client.py +3 -27
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/constants.py +0 -5
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/formatter.py +9 -4
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/parser.py +4 -1
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/serialization.py +2 -0
- twitter_cli-0.8.3/twitter_cli/timeutil.py +71 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/uv.lock +1 -1
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/.github/ISSUE_TEMPLATE/feature_request.yml +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/.github/workflows/ci.yml +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/.github/workflows/publish-clawhub.yml +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/.github/workflows/publish.yml +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/.gitignore +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/LICENSE +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/SCHEMA.md +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/SKILL.md +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/config.yaml +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/conftest.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/fixtures/followers_page.json +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/fixtures/list_timeline.json +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/fixtures/search_timeline.json +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/fixtures/tweet_detail.json +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/test_cli.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/test_config.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/test_config_normalization.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/test_filter.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/test_search.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/test_serialization.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/tests/test_smoke.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/__init__.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/cache.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/config.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/exceptions.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/filter.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/graphql.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/models.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/output.py +0 -0
- {twitter_cli-0.8.1 → twitter_cli-0.8.3}/twitter_cli/search.py +0 -0
|
@@ -70,7 +70,7 @@ body:
|
|
|
70
70
|
id: diagnostics
|
|
71
71
|
attributes:
|
|
72
72
|
label: Diagnostics
|
|
73
|
-
description: "Paste the output of `twitter
|
|
73
|
+
description: "Paste the output of `twitter -v <command>` here. This helps us diagnose cookie and auth issues quickly."
|
|
74
74
|
render: text
|
|
75
75
|
- type: textarea
|
|
76
76
|
id: logs
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: twitter-cli
|
|
3
|
-
Version: 0.8.
|
|
3
|
+
Version: 0.8.3
|
|
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
|
|
@@ -324,7 +324,7 @@ Mode behavior:
|
|
|
324
324
|
- `Invalid tweet JSON file`
|
|
325
325
|
- Regenerate input using `twitter feed --json > tweets.json`.
|
|
326
326
|
|
|
327
|
-
|
|
327
|
+
|
|
328
328
|
|
|
329
329
|
Structured error codes commonly include `not_authenticated`, `not_found`, `invalid_input`, `rate_limited`, and `api_error`.
|
|
330
330
|
|
|
@@ -365,27 +365,28 @@ twitter_cli/
|
|
|
365
365
|
|
|
366
366
|
twitter-cli ships with a [`SKILL.md`](./SKILL.md) so AI agents can execute common X/Twitter workflows.
|
|
367
367
|
|
|
368
|
-
####
|
|
368
|
+
#### [Skills CLI](https://github.com/vercel-labs/skills) (Recommended)
|
|
369
369
|
|
|
370
370
|
```bash
|
|
371
|
-
|
|
372
|
-
mkdir -p .agents/skills
|
|
373
|
-
git clone git@github.com:jackwener/twitter-cli.git .agents/skills/twitter-cli
|
|
374
|
-
|
|
375
|
-
# Or copy SKILL.md only
|
|
376
|
-
curl -o .agents/skills/twitter-cli/SKILL.md \
|
|
377
|
-
https://raw.githubusercontent.com/jackwener/twitter-cli/main/SKILL.md
|
|
371
|
+
npx skills add jackwener/twitter-cli
|
|
378
372
|
```
|
|
379
373
|
|
|
380
|
-
|
|
374
|
+
| Flag | Description |
|
|
375
|
+
| --- | --- |
|
|
376
|
+
| `-g` | Install globally (user-level, shared across projects) |
|
|
377
|
+
| `-a claude-code` | Target a specific agent |
|
|
378
|
+
| `-y` | Non-interactive mode |
|
|
381
379
|
|
|
382
|
-
|
|
380
|
+
#### Manual Install
|
|
383
381
|
|
|
384
382
|
```bash
|
|
385
|
-
|
|
383
|
+
mkdir -p .agents/skills
|
|
384
|
+
git clone git@github.com:jackwener/twitter-cli.git .agents/skills/twitter-cli
|
|
386
385
|
```
|
|
387
386
|
|
|
388
|
-
|
|
387
|
+
#### ~~OpenClaw / ClawHub~~ (Deprecated)
|
|
388
|
+
|
|
389
|
+
> ⚠️ ClawHub install method is deprecated and no longer supported. Use [Skills CLI](#skills-cli-recommended) or Manual Install above.
|
|
389
390
|
|
|
390
391
|
## 中文
|
|
391
392
|
|
|
@@ -572,7 +573,7 @@ score = likes_w * likes
|
|
|
572
573
|
- 或在弹出 Keychain 授权时点击 **"始终允许"**。
|
|
573
574
|
- 报错 `Twitter API error 404`:通常是 queryId 轮换,重试即可。
|
|
574
575
|
|
|
575
|
-
|
|
576
|
+
|
|
576
577
|
|
|
577
578
|
- 结构化错误码通常会区分 `not_authenticated`、`not_found`、`invalid_input`、`rate_limited`、`api_error`。
|
|
578
579
|
|
|
@@ -596,26 +597,29 @@ score = likes_w * likes
|
|
|
596
597
|
|
|
597
598
|
twitter-cli 提供了 [`SKILL.md`](./SKILL.md),可让 AI Agent 更稳定地调用本工具。
|
|
598
599
|
|
|
599
|
-
####
|
|
600
|
+
#### [Skills CLI](https://github.com/vercel-labs/skills)(推荐)
|
|
600
601
|
|
|
601
602
|
```bash
|
|
602
|
-
|
|
603
|
-
mkdir -p .agents/skills
|
|
604
|
-
git clone git@github.com:jackwener/twitter-cli.git .agents/skills/twitter-cli
|
|
605
|
-
|
|
606
|
-
# 或仅下载 SKILL.md
|
|
607
|
-
curl -o .agents/skills/twitter-cli/SKILL.md \
|
|
608
|
-
https://raw.githubusercontent.com/jackwener/twitter-cli/main/SKILL.md
|
|
603
|
+
npx skills add jackwener/twitter-cli
|
|
609
604
|
```
|
|
610
605
|
|
|
611
|
-
|
|
606
|
+
| 参数 | 说明 |
|
|
607
|
+
| --- | --- |
|
|
608
|
+
| `-g` | 全局安装(用户级别,跨项目共享) |
|
|
609
|
+
| `-a claude-code` | 指定目标 Agent |
|
|
610
|
+
| `-y` | 非交互模式 |
|
|
612
611
|
|
|
613
|
-
|
|
612
|
+
#### 手动安装
|
|
614
613
|
|
|
615
614
|
```bash
|
|
616
|
-
|
|
615
|
+
mkdir -p .agents/skills
|
|
616
|
+
git clone git@github.com:jackwener/twitter-cli.git .agents/skills/twitter-cli
|
|
617
617
|
```
|
|
618
618
|
|
|
619
|
+
#### ~~OpenClaw / ClawHub~~(已过时)
|
|
620
|
+
|
|
621
|
+
> ⚠️ ClawHub 安装方式已过时,不再支持。请使用上方的 Skills CLI 或手动安装。
|
|
622
|
+
|
|
619
623
|
### 更多工具
|
|
620
624
|
|
|
621
625
|
- [bilibili-cli](https://github.com/jackwener/bilibili-cli) — Bilibili 视频、用户、搜索与动态 CLI
|
|
@@ -292,7 +292,7 @@ Mode behavior:
|
|
|
292
292
|
- `Invalid tweet JSON file`
|
|
293
293
|
- Regenerate input using `twitter feed --json > tweets.json`.
|
|
294
294
|
|
|
295
|
-
|
|
295
|
+
|
|
296
296
|
|
|
297
297
|
Structured error codes commonly include `not_authenticated`, `not_found`, `invalid_input`, `rate_limited`, and `api_error`.
|
|
298
298
|
|
|
@@ -333,27 +333,28 @@ twitter_cli/
|
|
|
333
333
|
|
|
334
334
|
twitter-cli ships with a [`SKILL.md`](./SKILL.md) so AI agents can execute common X/Twitter workflows.
|
|
335
335
|
|
|
336
|
-
####
|
|
336
|
+
#### [Skills CLI](https://github.com/vercel-labs/skills) (Recommended)
|
|
337
337
|
|
|
338
338
|
```bash
|
|
339
|
-
|
|
340
|
-
mkdir -p .agents/skills
|
|
341
|
-
git clone git@github.com:jackwener/twitter-cli.git .agents/skills/twitter-cli
|
|
342
|
-
|
|
343
|
-
# Or copy SKILL.md only
|
|
344
|
-
curl -o .agents/skills/twitter-cli/SKILL.md \
|
|
345
|
-
https://raw.githubusercontent.com/jackwener/twitter-cli/main/SKILL.md
|
|
339
|
+
npx skills add jackwener/twitter-cli
|
|
346
340
|
```
|
|
347
341
|
|
|
348
|
-
|
|
342
|
+
| Flag | Description |
|
|
343
|
+
| --- | --- |
|
|
344
|
+
| `-g` | Install globally (user-level, shared across projects) |
|
|
345
|
+
| `-a claude-code` | Target a specific agent |
|
|
346
|
+
| `-y` | Non-interactive mode |
|
|
349
347
|
|
|
350
|
-
|
|
348
|
+
#### Manual Install
|
|
351
349
|
|
|
352
350
|
```bash
|
|
353
|
-
|
|
351
|
+
mkdir -p .agents/skills
|
|
352
|
+
git clone git@github.com:jackwener/twitter-cli.git .agents/skills/twitter-cli
|
|
354
353
|
```
|
|
355
354
|
|
|
356
|
-
|
|
355
|
+
#### ~~OpenClaw / ClawHub~~ (Deprecated)
|
|
356
|
+
|
|
357
|
+
> ⚠️ ClawHub install method is deprecated and no longer supported. Use [Skills CLI](#skills-cli-recommended) or Manual Install above.
|
|
357
358
|
|
|
358
359
|
## 中文
|
|
359
360
|
|
|
@@ -540,7 +541,7 @@ score = likes_w * likes
|
|
|
540
541
|
- 或在弹出 Keychain 授权时点击 **"始终允许"**。
|
|
541
542
|
- 报错 `Twitter API error 404`:通常是 queryId 轮换,重试即可。
|
|
542
543
|
|
|
543
|
-
|
|
544
|
+
|
|
544
545
|
|
|
545
546
|
- 结构化错误码通常会区分 `not_authenticated`、`not_found`、`invalid_input`、`rate_limited`、`api_error`。
|
|
546
547
|
|
|
@@ -564,26 +565,29 @@ score = likes_w * likes
|
|
|
564
565
|
|
|
565
566
|
twitter-cli 提供了 [`SKILL.md`](./SKILL.md),可让 AI Agent 更稳定地调用本工具。
|
|
566
567
|
|
|
567
|
-
####
|
|
568
|
+
#### [Skills CLI](https://github.com/vercel-labs/skills)(推荐)
|
|
568
569
|
|
|
569
570
|
```bash
|
|
570
|
-
|
|
571
|
-
mkdir -p .agents/skills
|
|
572
|
-
git clone git@github.com:jackwener/twitter-cli.git .agents/skills/twitter-cli
|
|
573
|
-
|
|
574
|
-
# 或仅下载 SKILL.md
|
|
575
|
-
curl -o .agents/skills/twitter-cli/SKILL.md \
|
|
576
|
-
https://raw.githubusercontent.com/jackwener/twitter-cli/main/SKILL.md
|
|
571
|
+
npx skills add jackwener/twitter-cli
|
|
577
572
|
```
|
|
578
573
|
|
|
579
|
-
|
|
574
|
+
| 参数 | 说明 |
|
|
575
|
+
| --- | --- |
|
|
576
|
+
| `-g` | 全局安装(用户级别,跨项目共享) |
|
|
577
|
+
| `-a claude-code` | 指定目标 Agent |
|
|
578
|
+
| `-y` | 非交互模式 |
|
|
580
579
|
|
|
581
|
-
|
|
580
|
+
#### 手动安装
|
|
582
581
|
|
|
583
582
|
```bash
|
|
584
|
-
|
|
583
|
+
mkdir -p .agents/skills
|
|
584
|
+
git clone git@github.com:jackwener/twitter-cli.git .agents/skills/twitter-cli
|
|
585
585
|
```
|
|
586
586
|
|
|
587
|
+
#### ~~OpenClaw / ClawHub~~(已过时)
|
|
588
|
+
|
|
589
|
+
> ⚠️ ClawHub 安装方式已过时,不再支持。请使用上方的 Skills CLI 或手动安装。
|
|
590
|
+
|
|
587
591
|
### 更多工具
|
|
588
592
|
|
|
589
593
|
- [bilibili-cli](https://github.com/jackwener/bilibili-cli) — Bilibili 视频、用户、搜索与动态 CLI
|
|
@@ -61,6 +61,13 @@
|
|
|
61
61
|
]
|
|
62
62
|
}
|
|
63
63
|
},
|
|
64
|
+
"note_tweet": {
|
|
65
|
+
"note_tweet_results": {
|
|
66
|
+
"result": {
|
|
67
|
+
"text": "Hello\nworld\n\nThis is the full text of a long tweet that goes beyond the 280 character limit and contains additional content that would be hidden behind Show More in the Twitter UI."
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
},
|
|
64
71
|
"views": {
|
|
65
72
|
"count": "1234"
|
|
66
73
|
}
|
|
@@ -373,7 +373,7 @@ def test_get_cookies_includes_keychain_hint_in_error(monkeypatch) -> None:
|
|
|
373
373
|
|
|
374
374
|
msg = str(exc_info.value)
|
|
375
375
|
assert "security unlock-keychain" in msg
|
|
376
|
-
assert "twitter
|
|
376
|
+
assert "twitter -v" in msg
|
|
377
377
|
|
|
378
378
|
|
|
379
379
|
def test_extract_in_process_returns_diagnostics_on_failure(monkeypatch) -> None:
|
|
@@ -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
|
)
|
|
@@ -26,6 +26,9 @@ def test_parse_home_timeline_fixture(fixture_loader) -> None:
|
|
|
26
26
|
assert [tweet.id for tweet in tweets] == ["1", "20"]
|
|
27
27
|
assert cursor == "cursor-bottom-1"
|
|
28
28
|
assert tweets[0].media[0].type == "photo"
|
|
29
|
+
# note_tweet full text should be preferred over legacy.full_text for long tweets
|
|
30
|
+
assert "Show More" in tweets[0].text
|
|
31
|
+
assert tweets[0].text.startswith("Hello\nworld\n")
|
|
29
32
|
assert tweets[0].urls == ["https://example.com/post"]
|
|
30
33
|
assert tweets[1].is_retweet is True
|
|
31
34
|
assert tweets[1].retweeted_by == "bob"
|
|
@@ -34,10 +37,9 @@ def test_parse_home_timeline_fixture(fixture_loader) -> None:
|
|
|
34
37
|
|
|
35
38
|
|
|
36
39
|
def test_parse_tweet_detail_fixture_with_nested_items(fixture_loader) -> None:
|
|
37
|
-
client = _make_client()
|
|
38
40
|
payload = fixture_loader("tweet_detail.json")
|
|
39
41
|
|
|
40
|
-
tweets, cursor =
|
|
42
|
+
tweets, cursor = parse_timeline_response(
|
|
41
43
|
payload,
|
|
42
44
|
lambda data: _deep_get(data, "data", "threaded_conversation_with_injections_v2", "instructions"),
|
|
43
45
|
)
|
|
@@ -47,10 +49,9 @@ def test_parse_tweet_detail_fixture_with_nested_items(fixture_loader) -> None:
|
|
|
47
49
|
|
|
48
50
|
|
|
49
51
|
def test_parse_search_timeline_fixture_with_module_items(fixture_loader) -> None:
|
|
50
|
-
client = _make_client()
|
|
51
52
|
payload = fixture_loader("search_timeline.json")
|
|
52
53
|
|
|
53
|
-
tweets, cursor =
|
|
54
|
+
tweets, cursor = parse_timeline_response(
|
|
54
55
|
payload,
|
|
55
56
|
lambda data: _deep_get(data, "data", "search_by_raw_query", "search_timeline", "timeline", "instructions"),
|
|
56
57
|
)
|
|
@@ -62,10 +63,9 @@ def test_parse_search_timeline_fixture_with_module_items(fixture_loader) -> None
|
|
|
62
63
|
|
|
63
64
|
|
|
64
65
|
def test_parse_list_timeline_fixture_with_visibility_wrapper(fixture_loader) -> None:
|
|
65
|
-
client = _make_client()
|
|
66
66
|
payload = fixture_loader("list_timeline.json")
|
|
67
67
|
|
|
68
|
-
tweets, cursor =
|
|
68
|
+
tweets, cursor = parse_timeline_response(
|
|
69
69
|
payload,
|
|
70
70
|
lambda data: _deep_get(data, "data", "list", "tweets_timeline", "timeline", "instructions"),
|
|
71
71
|
)
|
|
@@ -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()
|
|
@@ -578,7 +584,7 @@ def get_cookies() -> Dict[str, str]:
|
|
|
578
584
|
lines.append("Option 1: Set TWITTER_AUTH_TOKEN and TWITTER_CT0 environment variables")
|
|
579
585
|
lines.append("Option 2: Make sure you are logged into x.com in your browser (Arc/Chrome/Edge/Firefox/Brave)")
|
|
580
586
|
lines.append("")
|
|
581
|
-
lines.append("Run 'twitter
|
|
587
|
+
lines.append("Run 'twitter -v <command>' for debug diagnostics.")
|
|
582
588
|
raise RuntimeError("\n".join(lines))
|
|
583
589
|
|
|
584
590
|
# Verify only for explicit auth failures; transient endpoint issues are tolerated.
|
|
@@ -31,7 +31,6 @@ Write commands:
|
|
|
31
31
|
from __future__ import annotations
|
|
32
32
|
|
|
33
33
|
import logging
|
|
34
|
-
import os
|
|
35
34
|
import re
|
|
36
35
|
import inspect
|
|
37
36
|
import sys
|
|
@@ -737,10 +736,11 @@ def _print_show_hint():
|
|
|
737
736
|
@click.argument("index", type=click.IntRange(1))
|
|
738
737
|
@click.option("--max", "-n", "max_count", type=int, default=None, help="Max replies to fetch.")
|
|
739
738
|
@click.option("--full-text", is_flag=True, help="Show full reply text in table output.")
|
|
739
|
+
@click.option("--output", "-o", "output_file", type=str, default=None, help="Save tweet detail as JSON to file.")
|
|
740
740
|
@structured_output_options
|
|
741
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
|
|
742
|
+
def show(ctx, index, max_count, full_text, output_file, as_json, as_yaml):
|
|
743
|
+
# type: (Any, int, Optional[int], bool, Optional[str], bool, bool) -> None
|
|
744
744
|
"""View tweet #INDEX from the last feed/search results."""
|
|
745
745
|
compact = ctx.obj.get("compact", False)
|
|
746
746
|
|
|
@@ -769,6 +769,11 @@ def show(ctx, index, max_count, full_text, as_json, as_yaml):
|
|
|
769
769
|
except RuntimeError as exc:
|
|
770
770
|
_exit_with_error(exc)
|
|
771
771
|
|
|
772
|
+
if output_file:
|
|
773
|
+
Path(output_file).write_text(tweets_to_json(tweets), encoding="utf-8")
|
|
774
|
+
if rich_output:
|
|
775
|
+
console.print("💾 Saved to %s\n" % output_file)
|
|
776
|
+
|
|
772
777
|
_emit_tweet_detail(tweets, compact=compact, as_json=as_json, as_yaml=as_yaml, full_text=full_text)
|
|
773
778
|
|
|
774
779
|
|
|
@@ -1224,135 +1229,6 @@ def unbookmark(tweet_id, as_json, as_yaml):
|
|
|
1224
1229
|
_write_action("🔖", "Removing bookmark", "unbookmark_tweet", tweet_id, as_json=as_json, as_yaml=as_yaml)
|
|
1225
1230
|
|
|
1226
1231
|
|
|
1227
|
-
@cli.command(name="doctor")
|
|
1228
|
-
@structured_output_options
|
|
1229
|
-
def doctor(as_json, as_yaml):
|
|
1230
|
-
# type: (bool, bool) -> None
|
|
1231
|
-
"""Run diagnostics for cookie extraction and authentication.
|
|
1232
|
-
|
|
1233
|
-
Useful for troubleshooting auth issues and for pasting into bug reports.
|
|
1234
|
-
"""
|
|
1235
|
-
import platform
|
|
1236
|
-
|
|
1237
|
-
from .auth import (
|
|
1238
|
-
_diagnose_keychain_issues,
|
|
1239
|
-
_extract_in_process,
|
|
1240
|
-
_extract_via_subprocess,
|
|
1241
|
-
load_from_env,
|
|
1242
|
-
verify_cookies,
|
|
1243
|
-
)
|
|
1244
|
-
|
|
1245
|
-
info: Dict[str, Any] = {}
|
|
1246
|
-
mode = _structured_mode(as_json=as_json, as_yaml=as_yaml)
|
|
1247
|
-
|
|
1248
|
-
# -- System info --
|
|
1249
|
-
info["version"] = __version__
|
|
1250
|
-
info["python"] = sys.version.split()[0]
|
|
1251
|
-
info["platform"] = platform.platform()
|
|
1252
|
-
info["os"] = sys.platform
|
|
1253
|
-
|
|
1254
|
-
# -- Environment --
|
|
1255
|
-
is_ssh = bool(
|
|
1256
|
-
os.environ.get("SSH_CLIENT")
|
|
1257
|
-
or os.environ.get("SSH_TTY")
|
|
1258
|
-
or os.environ.get("SSH_CONNECTION")
|
|
1259
|
-
)
|
|
1260
|
-
info["ssh_session"] = is_ssh
|
|
1261
|
-
info["env_auth_token_set"] = bool(os.environ.get("TWITTER_AUTH_TOKEN"))
|
|
1262
|
-
info["env_ct0_set"] = bool(os.environ.get("TWITTER_CT0"))
|
|
1263
|
-
info["chrome_profile_override"] = os.environ.get("TWITTER_CHROME_PROFILE", "")
|
|
1264
|
-
|
|
1265
|
-
# -- Cookie extraction --
|
|
1266
|
-
env_cookies = load_from_env()
|
|
1267
|
-
info["env_cookies"] = "found" if env_cookies else "not set"
|
|
1268
|
-
|
|
1269
|
-
# In-process extraction
|
|
1270
|
-
in_proc_cookies, in_proc_diag = _extract_in_process()
|
|
1271
|
-
info["in_process"] = {
|
|
1272
|
-
"status": "ok" if in_proc_cookies else "failed",
|
|
1273
|
-
"diagnostics": in_proc_diag,
|
|
1274
|
-
}
|
|
1275
|
-
|
|
1276
|
-
# Subprocess extraction
|
|
1277
|
-
sub_cookies, sub_diag = _extract_via_subprocess()
|
|
1278
|
-
info["subprocess"] = {
|
|
1279
|
-
"status": "ok" if sub_cookies else "failed",
|
|
1280
|
-
"diagnostics": sub_diag,
|
|
1281
|
-
}
|
|
1282
|
-
|
|
1283
|
-
# Combined diagnostics
|
|
1284
|
-
all_diag = in_proc_diag + sub_diag
|
|
1285
|
-
cookies = in_proc_cookies or sub_cookies or env_cookies
|
|
1286
|
-
|
|
1287
|
-
# Keychain hint
|
|
1288
|
-
hint = _diagnose_keychain_issues(all_diag)
|
|
1289
|
-
if hint:
|
|
1290
|
-
info["keychain_hint"] = hint
|
|
1291
|
-
|
|
1292
|
-
# Verification
|
|
1293
|
-
if cookies:
|
|
1294
|
-
try:
|
|
1295
|
-
result = verify_cookies(
|
|
1296
|
-
cookies["auth_token"],
|
|
1297
|
-
cookies["ct0"],
|
|
1298
|
-
cookies.get("cookie_string"),
|
|
1299
|
-
)
|
|
1300
|
-
info["verification"] = "ok"
|
|
1301
|
-
info["screen_name"] = result.get("screen_name", "")
|
|
1302
|
-
except RuntimeError as exc:
|
|
1303
|
-
info["verification"] = "failed: %s" % exc
|
|
1304
|
-
else:
|
|
1305
|
-
info["verification"] = "skipped (no cookies)"
|
|
1306
|
-
|
|
1307
|
-
# -- Output --
|
|
1308
|
-
if _emit_mode_payload(info, mode):
|
|
1309
|
-
return
|
|
1310
|
-
|
|
1311
|
-
console.print("\n🩺 [bold]twitter-cli doctor[/bold]\n")
|
|
1312
|
-
console.print(" Version: %s" % info["version"])
|
|
1313
|
-
console.print(" Python: %s" % info["python"])
|
|
1314
|
-
console.print(" Platform: %s" % info["platform"])
|
|
1315
|
-
console.print(" SSH session: %s" % ("yes ⚠️" if is_ssh else "no"))
|
|
1316
|
-
console.print()
|
|
1317
|
-
|
|
1318
|
-
console.print("[bold]Environment:[/bold]")
|
|
1319
|
-
console.print(" TWITTER_AUTH_TOKEN: %s" % ("set ✅" if info["env_auth_token_set"] else "not set"))
|
|
1320
|
-
console.print(" TWITTER_CT0: %s" % ("set ✅" if info["env_ct0_set"] else "not set"))
|
|
1321
|
-
if info["chrome_profile_override"]:
|
|
1322
|
-
console.print(" TWITTER_CHROME_PROFILE: %s" % info["chrome_profile_override"])
|
|
1323
|
-
console.print()
|
|
1324
|
-
|
|
1325
|
-
console.print("[bold]Cookie Extraction:[/bold]")
|
|
1326
|
-
in_status = info["in_process"]["status"]
|
|
1327
|
-
console.print(
|
|
1328
|
-
" In-process: %s" % ("[green]ok ✅[/green]" if in_status == "ok" else "[red]failed ❌[/red]")
|
|
1329
|
-
)
|
|
1330
|
-
for d in info["in_process"]["diagnostics"]:
|
|
1331
|
-
console.print(" [dim]• %s[/dim]" % d)
|
|
1332
|
-
|
|
1333
|
-
sub_status = info["subprocess"]["status"]
|
|
1334
|
-
console.print(
|
|
1335
|
-
" Subprocess: %s" % ("[green]ok ✅[/green]" if sub_status == "ok" else "[red]failed ❌[/red]")
|
|
1336
|
-
)
|
|
1337
|
-
for d in info["subprocess"]["diagnostics"]:
|
|
1338
|
-
console.print(" [dim]• %s[/dim]" % d)
|
|
1339
|
-
console.print()
|
|
1340
|
-
|
|
1341
|
-
if hint:
|
|
1342
|
-
console.print("[yellow]💡 Hint:[/yellow]")
|
|
1343
|
-
for line in hint.splitlines():
|
|
1344
|
-
console.print(" [yellow]%s[/yellow]" % line)
|
|
1345
|
-
console.print()
|
|
1346
|
-
|
|
1347
|
-
v = info["verification"]
|
|
1348
|
-
if v == "ok":
|
|
1349
|
-
screen = info.get("screen_name", "")
|
|
1350
|
-
console.print("[green]✅ Authentication: OK[/green]%s" % (" (@%s)" % screen if screen else ""))
|
|
1351
|
-
elif v.startswith("failed"):
|
|
1352
|
-
console.print("[red]❌ Authentication: %s[/red]" % v)
|
|
1353
|
-
else:
|
|
1354
|
-
console.print("[yellow]⚠️ Authentication: %s[/yellow]" % v)
|
|
1355
|
-
console.print()
|
|
1356
1232
|
|
|
1357
1233
|
|
|
1358
1234
|
if __name__ == "__main__":
|
|
@@ -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
|
|
|
@@ -125,7 +128,7 @@ def print_tweet_detail(tweet: Tweet, console: Optional[Console] = None) -> None:
|
|
|
125
128
|
qt = tweet.quoted_tweet
|
|
126
129
|
body_parts.append("")
|
|
127
130
|
body_parts.append("┌── Quoted @%s ──" % qt.author.screen_name)
|
|
128
|
-
body_parts.append(qt.text
|
|
131
|
+
body_parts.append(qt.text)
|
|
129
132
|
|
|
130
133
|
body_parts.append("")
|
|
131
134
|
body_parts.append(
|
|
@@ -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(
|
|
@@ -246,9 +246,12 @@ def parse_tweet_result(result, depth=0):
|
|
|
246
246
|
if is_retweet:
|
|
247
247
|
retweeted_by = user_core.get("screen_name") or user_legacy.get("screen_name", "unknown")
|
|
248
248
|
|
|
249
|
+
# Prefer note_tweet full text for long tweets ("Show More")
|
|
250
|
+
note_text = _deep_get(actual_data, "note_tweet", "note_tweet_results", "result", "text")
|
|
251
|
+
|
|
249
252
|
return Tweet(
|
|
250
253
|
id=actual_data.get("rest_id", ""),
|
|
251
|
-
text=actual_legacy.get("full_text", ""),
|
|
254
|
+
text=note_text or actual_legacy.get("full_text", ""),
|
|
252
255
|
author=author,
|
|
253
256
|
metrics=Metrics(
|
|
254
257
|
likes=_parse_int(actual_legacy.get("favorite_count"), 0),
|
|
@@ -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
|