Download images or videos from an X (Twitter) link to ~/Downloads.
Dependencies
yt-dlp(installed)
Execution flow
1. Parse the input
Extract the X/Twitter URL from the user input. Supported formats:
https://x.com/user/status/123456https://twitter.com/user/status/123456https://mobile.twitter.com/user/status/123456- URLs with query parameters (yt-dlp automatically handles
?s=20and other tracking parameters)
Shortened links (t.co) are resolved first:curl -Ls -o /dev/null -w '%{url_effective}' "SHORT_URL"
If the user did not provide a URL, use AskUserQuestion to request one.
2. Try downloading directly (video first)
Download directly with yt-dlp, no need to probe first:
yt-dlp -o "~/Downloads/%(uploader)s_%(id)s.%(ext)s" "URL"
If successful (video tweet), done. Skip to step 4 to report the result.
3. When video download fails, extract images
yt-dlp may error on image-only tweets. In this case use --dump-json to extract the image URLs:
yt-dlp --dump-json "URL" 2>&1
Interpret the result:
- JSON contains a
thumbnailsarray → extract the image URLs - JSON is empty or errors with
no video→ the tweet has no media, tell the user "该推文不包含可下载的图片或视频" - Error contains
login/authentication→ login required (see troubleshooting) - Other errors → report the specific error message
Image download:
From the JSON's thumbnails array, extract all image URLs, replace name=small or name=medium with name=orig to get the original image, then download them one by one:
curl -L -o ~/Downloads/tweet_ID_1.jpg "https://pbs.twimg.com/media/xxx?format=jpg&name=orig"
curl -L -o ~/Downloads/tweet_ID_2.jpg "https://pbs.twimg.com/media/yyy?format=jpg&name=orig"
The file extension follows the format parameter in the URL (jpg/png/webp).
4. Report the result
After the download is complete, use ls -lh to list the downloaded files: file name, size, path.
Troubleshooting
Login required
When yt-dlp errors with login / Sign in / age-restricted , add --cookies-from-browser chrome:
yt-dlp --cookies-from-browser chrome -o "~/Downloads/%(uploader)s_%(id)s.%(ext)s" "URL"
Tweet has no media
Text-only tweets have no downloadable media. Just tell the user.