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