Skip to content

Commit 1d0a2f2

Browse files
committed
feat(media): 📝 add example for media upload api v2
1 parent 14ad8b8 commit 1d0a2f2

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

examples/media_upload_v2.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""
2+
Upload a video with media upload v2
3+
"""
4+
5+
import os
6+
7+
from pytwitter import Api
8+
9+
consumer_key = "your app consumer key"
10+
consumer_secret = "your app consumer secret"
11+
access_token = "your access token"
12+
access_secret = "your access token secret"
13+
14+
# init api with OAuth1.0
15+
api = Api(
16+
consumer_key=consumer_key,
17+
consumer_secret=consumer_secret,
18+
access_token=access_token,
19+
access_secret=access_secret,
20+
)
21+
22+
video_path = "path/to/video.mp4"
23+
24+
# init media upload
25+
26+
init_resp = api.upload_media_chunked_init_v2(
27+
total_bytes=os.path.getsize(video_path),
28+
media_type="video/mp4",
29+
media_category="tweet_video",
30+
)
31+
32+
print(f"Init response: {init_resp}")
33+
34+
# upload by chunk
35+
chunk_size = 1024 * 1024 * 1
36+
segment_index = 0
37+
38+
with open(video_path, "rb") as f:
39+
while True:
40+
chunk = f.read(chunk_size)
41+
if not chunk:
42+
break
43+
44+
chunk_resp = api.upload_media_chunked_append_v2(
45+
media_id=init_resp.data.id,
46+
segment_index=segment_index,
47+
media=chunk,
48+
)
49+
print(f"Chunk response: {chunk_resp}")
50+
51+
print("Finished chunk upload")
52+
53+
# finalize upload
54+
finalize_resp = api.upload_media_chunked_finalize_v2(
55+
media_id=init_resp.data.id,
56+
)
57+
print(f"Finalize response: {finalize_resp}")
58+
59+
# Now you can use the media to create tweet
60+
tweet_resp = api.create_tweet(
61+
text="Tweet with video", media_media_ids=[init_resp.data.id]
62+
)
63+
64+
print(f"Tweet response: {tweet_resp}")

0 commit comments

Comments
 (0)