Compare commits

...
34 Commits
Author SHA1 Message Date
afkarxyz ee92174773 v2.4.5 2025-05-08 07:54:31 +07:00
afkarxyz f08ce57feb Update README.md 2025-05-06 15:37:20 +07:00
afkarxyz 4f21321e42 Update README.md 2025-05-04 06:24:24 +07:00
afkarxyz c8b7a5365a v2.4 2025-05-04 06:22:28 +07:00
afkarxyz 1049b544c5 v2.4 2025-05-04 06:19:03 +07:00
afkarxyz e7db97a936 Small fix 2025-04-23 18:32:29 +07:00
afkarxyz af1280b798 Update v2.3 2025-04-23 18:27:12 +07:00
afkarxyz 4f6004a501 Update v2.3 2025-04-23 18:23:34 +07:00
afkarxyz e7141cd8d1 Update v2.2 2025-04-22 22:01:51 +07:00
afkarxyz 4d6f4d904a Update v2.2 2025-04-22 21:57:59 +07:00
afkarxyz 4081e6aacf Update README.md 2025-04-22 21:45:29 +07:00
afkarxyz 2b405a16a7 Update v2.1 2025-04-22 05:35:30 +07:00
afkarxyz 5e658c05d4 Update v2.1 2025-04-22 05:22:34 +07:00
afkarxyz b26dd0b2af Update TwitterXMediaBatchDownloader.py 2025-03-25 19:44:54 +07:00
afkarxyz 28422dcf1d Update v2.0 2025-03-25 18:47:21 +07:00
afkarxyz 46e09532fc Update v2.0 2025-03-25 18:44:06 +07:00
afkarxyz 967d91d370 Update README.md 2025-03-25 18:42:57 +07:00
afkarxyz 2ff0242e32 Update README.md 2025-03-24 04:41:38 +07:00
afkarxyz 1e1d612807 Update README.md 2025-03-23 23:59:41 +07:00
afkarxyz 9821dd8c65 Update README.md 2025-03-23 23:59:07 +07:00
afkarxyz 46bb7d38f7 Update README.md 2025-03-23 23:58:34 +07:00
afkarxyz 112f5992c4 Batch Request 2025-03-23 23:48:06 +07:00
afkarxyz 178b3c490f Update v1.9 2025-03-23 23:35:15 +07:00
afkarxyz bb1c0dccae Merge branch 'main' of https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader 2025-03-23 23:31:55 +07:00
afkarxyz 0cf5316745 Update v1.9 2025-03-23 23:31:44 +07:00
afkarxyz c3493944e8 Update README.md 2025-03-23 23:30:54 +07:00
afkarxyz c656459171 Update README.md 2025-03-23 21:11:17 +07:00
afkarxyz 0e14f92244 Update README.md 2025-03-23 18:40:24 +07:00
afkarxyz fad4434753 Update README.md 2025-03-23 18:34:41 +07:00
afkarxyz 77a9c83f4d Update v1.8 2025-03-23 18:30:14 +07:00
afkarxyz 7fa277931c Update v1.8 2025-03-23 18:26:37 +07:00
afkarxyz be080481bf Update README.md 2025-03-23 18:24:45 +07:00
afkarxyz 8a720e3e2b Update README.md 2025-03-04 09:16:57 +07:00
afkarxyz 48a672e0bd Update README.md 2025-03-04 09:10:50 +07:00
6 changed files with 991 additions and 358 deletions

No files matched your search

+165 -35
View File
@@ -4,42 +4,95 @@ import os
from datetime import datetime from datetime import datetime
from gallery_dl.extractor import twitter from gallery_dl.extractor import twitter
def get_metadata(username, auth_token): def get_metadata(username, auth_token, timeline_type="timeline", batch_size=0, page=0, output_file=None):
url = f"https://x.com/{username}/timeline" url = f"https://x.com/{username}/{timeline_type}"
match = re.match(twitter.TwitterTimelineExtractor.pattern, url) if timeline_type == "media":
extractor_class = twitter.TwitterMediaExtractor
elif timeline_type == "tweets":
extractor_class = twitter.TwitterTweetsExtractor
elif timeline_type == "with_replies":
extractor_class = twitter.TwitterRepliesExtractor
else:
extractor_class = twitter.TwitterTimelineExtractor
match = re.match(extractor_class.pattern, url)
if not match: if not match:
raise ValueError(f"Invalid URL: {url}") raise ValueError(f"Invalid URL for {timeline_type}: {url}")
extractor = twitter.TwitterTimelineExtractor(match) extractor = extractor_class(match)
extractor.config = lambda key, default=None: { config_dict = {
"cookies": { "cookies": {
"auth_token": auth_token "auth_token": auth_token
} }
}.get(key, default) }
if batch_size > 0:
config_dict["count"] = batch_size
extractor.config = lambda key, default=None: config_dict.get(key, default)
extractor.initialize() extractor.initialize()
output = { if output_file is None:
current_dir = os.path.dirname(os.path.abspath(__file__))
output_file = os.path.join(current_dir, f"{username}_{timeline_type}.json")
structured_output = {
'account_info': {}, 'account_info': {},
'total_urls': 0, 'total_urls': 0,
'timeline': [] 'timeline': []
} }
for item in extractor: if page > 0 and os.path.exists(output_file):
if isinstance(item, tuple) and len(item) >= 3: try:
media_url = item[1] with open(output_file, 'r', encoding='utf-8') as f:
tweet_data = item[2] structured_output = json.load(f)
print(f"Loaded existing data with {structured_output['total_urls']} items from {output_file}")
except json.JSONDecodeError:
print(f"Warning: Could not load existing data from {output_file}, starting fresh")
if not output['account_info']: iterator = iter(extractor)
if 'user' in tweet_data:
if batch_size > 0 and page > 0:
items_to_skip = page * batch_size
print(f"Skipping {items_to_skip} items for page {page}...")
if hasattr(extractor, '_cursor') and extractor._cursor:
print(f"Using cursor: {extractor._cursor}")
else:
skipped = 0
try:
for _ in range(items_to_skip):
next(iterator)
skipped += 1
except StopIteration:
print(f"Warning: Could only skip {skipped} items")
batch_items = []
new_timeline_entries = []
items_to_fetch = batch_size if batch_size > 0 else float('inf')
items_fetched = 0
try:
while items_fetched < items_to_fetch:
item = next(iterator)
batch_items.append(item)
items_fetched += 1
if isinstance(item, tuple) and len(item) >= 3:
media_url = item[1]
tweet_data = item[2]
if not structured_output['account_info'] and 'user' in tweet_data:
user = tweet_data['user'] user = tweet_data['user']
user_date = user.get('date', '') user_date = user.get('date', '')
if isinstance(user_date, datetime): if isinstance(user_date, datetime):
user_date = user_date.strftime("%Y-%m-%d %H:%M:%S") user_date = user_date.strftime("%Y-%m-%d %H:%M:%S")
output['account_info'] = { structured_output['account_info'] = {
'name': user.get('name', ''), 'name': user.get('name', ''),
'nick': user.get('nick', ''), 'nick': user.get('nick', ''),
'date': user_date, 'date': user_date,
@@ -49,31 +102,108 @@ def get_metadata(username, auth_token):
'statuses_count': user.get('statuses_count', 0) 'statuses_count': user.get('statuses_count', 0)
} }
if 'pbs.twimg.com' in media_url or 'video.twimg.com' in media_url: if 'pbs.twimg.com' in media_url or 'video.twimg.com' in media_url:
tweet_date = tweet_data.get('date', datetime.now()) tweet_date = tweet_data.get('date', datetime.now())
if isinstance(tweet_date, datetime): if isinstance(tweet_date, datetime):
tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S") tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S")
timeline_entry = { timeline_entry = {
'url': media_url, 'url': media_url,
'date': tweet_date, 'date': tweet_date,
'tweet_id': tweet_data.get('tweet_id', 0), 'tweet_id': tweet_data.get('tweet_id', 0),
} }
if 'type' in tweet_data: if 'type' in tweet_data:
timeline_entry['type'] = tweet_data['type'] timeline_entry['type'] = tweet_data['type']
output['timeline'].append(timeline_entry) new_timeline_entries.append(timeline_entry)
output['total_urls'] += 1 structured_output['total_urls'] += 1
except StopIteration:
pass
current_dir = os.path.dirname(os.path.abspath(__file__)) structured_output['timeline'].extend(new_timeline_entries)
output_file = os.path.join(current_dir, f"{username}.json")
with open(output_file, 'w', encoding='utf-8') as f: with open(output_file, 'w', encoding='utf-8') as f:
json.dump(output, f, ensure_ascii=False, indent=2) json.dump(structured_output, f, ensure_ascii=False, indent=2)
return output if batch_size > 0:
print(f"Page {page}: Added {len(new_timeline_entries)} media URLs. Total URLs: {structured_output['total_urls']}")
else:
print(f"Added {len(new_timeline_entries)} media URLs. Total URLs: {structured_output['total_urls']}")
username = "" cursor_info = None
auth_token = "" if hasattr(extractor, '_cursor') and extractor._cursor:
get_metadata(username, auth_token) cursor_info = extractor._cursor
print(f"Current cursor: {cursor_info}")
return {
"items": batch_items,
"structured_output": structured_output,
"new_entries": len(new_timeline_entries),
"total_urls": structured_output['total_urls'],
"page": page,
"batch_size": batch_size,
"has_more": batch_size > 0 and items_fetched == batch_size,
"cursor": cursor_info
}
def continue_metadata_fetch(username, auth_token, timeline_type="media", batch_size=100, max_pages=None):
current_dir = os.path.dirname(os.path.abspath(__file__))
output_file = os.path.join(current_dir, f"{username}_{timeline_type}.json")
page = 0
total_urls = 0
has_more = True
if os.path.exists(output_file):
try:
with open(output_file, 'r', encoding='utf-8') as f:
existing_data = json.load(f)
total_urls = existing_data.get('total_urls', 0)
page = total_urls // batch_size if batch_size > 0 else 0
print(f"Continuing from page {page} with {total_urls} existing URLs")
except json.JSONDecodeError:
print(f"Warning: Could not load existing data from {output_file}, starting fresh")
while has_more and (max_pages is None or page < max_pages):
result = get_metadata(
username=username,
auth_token=auth_token,
timeline_type=timeline_type,
batch_size=batch_size,
page=page,
output_file=output_file
)
has_more = result["has_more"]
total_urls = result["total_urls"]
if not has_more:
print(f"No more items to fetch. Total URLs: {total_urls}")
break
page += 1
return total_urls
# Usage
if __name__ == "__main__":
username = "takomayuyi"
auth_token = ""
# Example 1: Non-batch mode - fetch all items at once
# This will fetch all items without pagination
# result = get_metadata(username, auth_token, "media")
# print(f"Non-batch mode: Added {result['new_entries']} media URLs")
# Example 2: Batch mode - fetch items in pages
# This will fetch only the specified page with the given batch size
result = get_metadata(username, auth_token, "media", batch_size=100, page=0)
print(f"Batch mode: Added {result['new_entries']} media URLs (page 0)")
# To fetch the next page:
# result = get_metadata(username, auth_token, "media", batch_size=100, page=1)
# To automatically fetch all pages in batch mode:
# total = continue_metadata_fetch(username, auth_token, "media", batch_size=100)
# print(f"Total media URLs fetched across all pages: {total}")
+141 -15
View File
@@ -3,33 +3,159 @@ import re
import os import os
from gallery_dl.extractor import twitter from gallery_dl.extractor import twitter
def get_metadata(username, auth_token): def get_metadata(username, auth_token, timeline_type="timeline", batch_size=0, page=0, output_file=None):
url = f"https://x.com/{username}/timeline" url = f"https://x.com/{username}/{timeline_type}"
match = re.match(twitter.TwitterTimelineExtractor.pattern, url) if timeline_type == "media":
extractor_class = twitter.TwitterMediaExtractor
elif timeline_type == "tweets":
extractor_class = twitter.TwitterTweetsExtractor
elif timeline_type == "with_replies":
extractor_class = twitter.TwitterRepliesExtractor
else:
extractor_class = twitter.TwitterTimelineExtractor
match = re.match(extractor_class.pattern, url)
if not match: if not match:
raise ValueError(f"Invalid URL: {url}") raise ValueError(f"Invalid URL for {timeline_type}: {url}")
extractor = twitter.TwitterTimelineExtractor(match) extractor = extractor_class(match)
extractor.config = lambda key, default=None: { config_dict = {
"cookies": { "cookies": {
"auth_token": auth_token "auth_token": auth_token
} }
}.get(key, default) }
if batch_size > 0:
config_dict["count"] = batch_size
extractor.config = lambda key, default=None: config_dict.get(key, default)
extractor.initialize() extractor.initialize()
all_items = [] if output_file is None:
for item in extractor: current_dir = os.path.dirname(os.path.abspath(__file__))
all_items.append(item) output_file = os.path.join(current_dir, f"{username}_{timeline_type}.json")
current_dir = os.path.dirname(os.path.abspath(__file__)) all_items = []
output_file = os.path.join(current_dir, f"{username}.json") if page > 0 and os.path.exists(output_file):
try:
with open(output_file, 'r', encoding='utf-8') as f:
all_items = json.load(f)
print(f"Loaded {len(all_items)} existing items from {output_file}")
except json.JSONDecodeError:
print(f"Warning: Could not load existing data from {output_file}, starting fresh")
iterator = iter(extractor)
if batch_size > 0 and page > 0:
items_to_skip = page * batch_size
print(f"Skipping {items_to_skip} items for page {page}...")
if hasattr(extractor, '_cursor') and extractor._cursor:
print(f"Using cursor: {extractor._cursor}")
else:
skipped = 0
try:
for _ in range(items_to_skip):
next(iterator)
skipped += 1
except StopIteration:
print(f"Warning: Could only skip {skipped} items")
batch_items = []
if batch_size > 0:
try:
for _ in range(batch_size):
item = next(iterator)
batch_items.append(item)
except StopIteration:
pass
else:
batch_items = list(iterator)
all_items.extend(batch_items)
with open(output_file, 'w', encoding='utf-8') as f: with open(output_file, 'w', encoding='utf-8') as f:
json.dump(all_items, f, indent=2, default=str) json.dump(all_items, f, indent=2, default=str)
username = "" if batch_size > 0:
auth_token = "" print(f"Page {page}: Retrieved {len(batch_items)} items. Total items: {len(all_items)}")
get_metadata(username, auth_token) else:
print(f"Retrieved {len(batch_items)} items total")
cursor_info = None
if hasattr(extractor, '_cursor') and extractor._cursor:
cursor_info = extractor._cursor
print(f"Current cursor: {cursor_info}")
return {
"items": batch_items,
"total_items": len(all_items),
"page": page,
"batch_size": batch_size,
"has_more": batch_size > 0 and len(batch_items) == batch_size,
"cursor": cursor_info
}
def continue_metadata_fetch(username, auth_token, timeline_type="media", batch_size=100, max_pages=None):
current_dir = os.path.dirname(os.path.abspath(__file__))
output_file = os.path.join(current_dir, f"{username}_{timeline_type}.json")
page = 0
total_items = 0
has_more = True
if os.path.exists(output_file):
try:
with open(output_file, 'r', encoding='utf-8') as f:
existing_data = json.load(f)
total_items = len(existing_data)
page = total_items // batch_size
print(f"Continuing from page {page} with {total_items} existing items")
except json.JSONDecodeError:
print(f"Warning: Could not load existing data from {output_file}, starting fresh")
while has_more and (max_pages is None or page < max_pages):
result = get_metadata(
username=username,
auth_token=auth_token,
timeline_type=timeline_type,
batch_size=batch_size,
page=page,
output_file=output_file
)
has_more = result["has_more"]
total_items = result["total_items"]
if not has_more:
print(f"No more items to fetch. Total items: {total_items}")
break
page += 1
return total_items
# Usage
if __name__ == "__main__":
username = "takomayuyi"
auth_token = ""
# Example 1: Non-batch mode - fetch all items at once
# This will fetch all items without pagination
# result = get_metadata(username, auth_token, "media")
# print(f"Non-batch mode: Retrieved {len(result['items'])} items")
# Example 2: Batch mode - fetch items in pages
# This will fetch only the specified page with the given batch size
result = get_metadata(username, auth_token, "media", batch_size=100, page=0)
print(f"Batch mode: Retrieved {len(result['items'])} items (page 0)")
# To fetch the next page:
# result = get_metadata(username, auth_token, "media", batch_size=100, page=1)
# To automatically fetch all pages in batch mode:
# total = continue_metadata_fetch(username, auth_token, "media", batch_size=100)
# print(f"Total items fetched across all pages: {total}")
+17 -23
View File
@@ -3,44 +3,38 @@
![TwitterXMediaBatchDownloader](https://github.com/user-attachments/assets/354d7470-c01c-4aa6-9da1-ea6c42d27330) ![TwitterXMediaBatchDownloader](https://github.com/user-attachments/assets/354d7470-c01c-4aa6-9da1-ea6c42d27330)
<div align="center"> <div align="center">
<b>Twitter/X Media Batch Downloader</b> is a GUI tool that allows users to download all media, including images and videos, in their original quality from Twitter/X accounts, even withheld accounts, using <code>gallery-dl</code> <b>Twitter/X Media Batch Downloader</b> is a GUI tool that allows users to download all media, including images and videos, in their original quality from Twitter/X accounts using <code>gallery-dl</code>
</div> </div>
## Download ## 📥 Download
- Download the latest version of [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v1.7/TwitterXMediaBatchDownloader.exe) - Download the latest version of [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v2.4.5/TwitterXMediaBatchDownloader.exe)
- If you're familiar with **userscripts**, please install it [here](https://greasyfork.org/en/scripts/523157-twitter-x-media-batch-downloader) - If you're familiar with **userscripts**, please install it [here](https://greasyfork.org/en/scripts/523157)
## Features ## ✨ Features
- Uses the powerful `gallery-dl` library, similar to `yt-dlp` - Powered by `gallery-dl`, similar to `yt-dlp`
- The ability to download media from **Withheld Accounts** _(maybe requires checking the **Use gallery-dl API** option)_ - **Choose media type**: All (Image + GIF + Video) or specific (Image/GIF/Video)
- Option to choose the media type to download: **All Media** (Image + GIF + Video) or just **Image/GIF/Video** - Downloads in original quality
- Download images and videos in original quality
## Screenshots ## 🖼️ Screenshots
![image](https://github.com/user-attachments/assets/085cdcee-5272-41bb-8612-06737c0ebe32) ![image](https://github.com/user-attachments/assets/718c5725-6323-4ece-8552-a467767de039)
![image](https://github.com/user-attachments/assets/3e71f14b-c4f0-4e86-87d5-9217d88cb0c2) ![python_7NZpAQ8RQi](https://github.com/user-attachments/assets/9982e4f5-a4b2-4d1b-9481-7bf7db700663)
![image](https://github.com/user-attachments/assets/c4e086c2-d4d5-4eee-8bab-dba8e5fdd90d) ![image](https://github.com/user-attachments/assets/e8960328-f38d-4944-91a4-31b792ce47e3)
> Downloading from **Withheld Accounts** > [!Important]
> Use **Batch** if the items to be downloaded are in the thousands.
![image](https://github.com/user-attachments/assets/f5e301cf-9700-4986-a87d-8424be40db5c) ## 🔑 How to Obtain Auth Token
![image](https://github.com/user-attachments/assets/92f814b1-069f-4605-b31f-8a5ff8dc0f17)
![image](https://github.com/user-attachments/assets/c6e7dc0d-659d-456e-b30c-6cca66fe9359)
## How to Obtain Auth Token
> [!Warning] > [!Warning]
> - I suggest not using the **main account** to obtain the token. > - I suggest not using the **main account** to obtain the token.
> - You can use https://temp-mail.io to register a Twitter account. > - You can use https://temp-mail.io to register a Twitter account.
> - Using an auth token or cookies has the potential to get the **account suspended.** > - Using an auth token or cookies has the potential to get the **account suspended.**
> - If too many media files are fetched, it will trigger a **rate limit**, and the media retrieval will fail. > - If too many media files are fetched, it may trigger a **rate limit**, and the media retrieval will fail, try enabling Batch mode.
1. Go to [Twitter's website](https://www.x.com/) 1. Go to [Twitter's website](https://www.x.com/)
2. Log into your account 2. Log into your account
@@ -55,4 +49,4 @@
> Developer Tools > Developer Tools
![image](https://github.com/user-attachments/assets/50f819da-7490-4f3c-b130-c5a3ee482e2d) ![image](https://github.com/user-attachments/assets/8e81dd8f-f8be-4254-9cf6-cacfa97743e9)
File diff suppressed because it is too large. Load diff
+186
View File
@@ -0,0 +1,186 @@
import re
import json
from datetime import datetime
from gallery_dl.extractor import twitter
def get_metadata(username, auth_token, timeline_type="timeline", batch_size=0, page=0, media_type="all"):
url = f"https://x.com/{username}/{timeline_type}"
if timeline_type == "media":
extractor_class = twitter.TwitterMediaExtractor
elif timeline_type == "tweets":
extractor_class = twitter.TwitterTweetsExtractor
elif timeline_type == "with_replies":
extractor_class = twitter.TwitterRepliesExtractor
else:
extractor_class = twitter.TwitterTimelineExtractor
match = re.match(extractor_class.pattern, url)
if not match:
raise ValueError(f"Invalid URL for {timeline_type}: {url}")
extractor = extractor_class(match)
config_dict = {
"cookies": {
"auth_token": auth_token
}
}
if batch_size > 0:
config_dict["count"] = batch_size
extractor.config = lambda key, default=None: config_dict.get(key, default)
try:
extractor.initialize()
api = twitter.TwitterAPI(extractor)
try:
if username.startswith("id:"):
user = api.user_by_rest_id(username[3:])
else:
user = api.user_by_screen_name(username)
if "legacy" in user and user["legacy"].get("withheld_scope"):
raise ValueError("withheld")
except Exception as e:
error_msg = str(e).lower()
if "withheld" in error_msg or (hasattr(e, "response") and "withheld" in str(e.response.text).lower()):
raise ValueError("withheld")
raise
structured_output = {
'account_info': {},
'total_urls': 0,
'timeline': []
}
iterator = iter(extractor)
if batch_size > 0 and page > 0:
items_to_skip = page * batch_size
if hasattr(extractor, '_cursor') and extractor._cursor:
pass
else:
skipped = 0
try:
for _ in range(items_to_skip):
next(iterator)
skipped += 1
except StopIteration:
pass
new_timeline_entries = []
items_to_fetch = batch_size if batch_size > 0 else float('inf')
items_fetched = 0
try:
while items_fetched < items_to_fetch:
item = next(iterator)
items_fetched += 1
if isinstance(item, tuple) and len(item) >= 3:
media_url = item[1]
tweet_data = item[2]
if not structured_output['account_info'] and 'user' in tweet_data:
user = tweet_data['user']
user_date = user.get('date', '')
if isinstance(user_date, datetime):
user_date = user_date.strftime("%Y-%m-%d %H:%M:%S")
structured_output['account_info'] = {
'name': user.get('name', ''),
'nick': user.get('nick', ''),
'date': user_date,
'followers_count': user.get('followers_count', 0),
'friends_count': user.get('friends_count', 0),
'profile_image': user.get('profile_image', ''),
'statuses_count': user.get('statuses_count', 0)
}
if 'pbs.twimg.com' in media_url or 'video.twimg.com' in media_url:
tweet_date = tweet_data.get('date', datetime.now())
if isinstance(tweet_date, datetime):
tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S")
timeline_entry = {
'url': media_url,
'date': tweet_date,
'tweet_id': tweet_data.get('tweet_id', 0),
}
if 'type' in tweet_data:
timeline_entry['type'] = tweet_data['type']
if media_type == 'all' or (
(media_type == 'image' and 'pbs.twimg.com' in media_url and tweet_data.get('type') == 'photo') or
(media_type == 'video' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'video') or
(media_type == 'gif' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'animated_gif')
):
new_timeline_entries.append(timeline_entry)
structured_output['total_urls'] += 1
except StopIteration:
pass
structured_output['timeline'].extend(new_timeline_entries)
cursor_info = None
if hasattr(extractor, '_cursor') and extractor._cursor:
cursor_info = extractor._cursor
structured_output['metadata'] = {
"new_entries": len(new_timeline_entries),
"page": page,
"batch_size": batch_size,
"has_more": batch_size > 0 and items_fetched == batch_size,
"cursor": cursor_info
}
if not structured_output['account_info']:
raise ValueError("Failed to fetch account information. Please check the username and auth token.")
return structured_output
except Exception as e:
error_msg = str(e).lower()
if "withheld" in error_msg or e.__class__.__name__ == "ValueError" and str(e) == "withheld":
return {"error": "withheld"}
else:
error_str = str(e)
if error_str == "None":
return {"error": "null"}
else:
return {"error": error_str}
def main():
username = ""
auth_token = ""
timeline_type = "media"
batch_size = 100
page = 0
media_type = "all"
try:
data = get_metadata(
username=username,
auth_token=auth_token,
timeline_type=timeline_type,
batch_size=batch_size,
page=page,
media_type=media_type
)
print(json.dumps(data, ensure_ascii=False, indent=2))
except Exception as e:
error_str = str(e)
if error_str == "None":
print(json.dumps({"error": "null"}, ensure_ascii=False))
else:
print(json.dumps({"error": error_str}, ensure_ascii=False))
if __name__ == '__main__':
main()
+1 -1
View File
@@ -1,3 +1,3 @@
{ {
"version": "1.7" "version": "2.4.5"
} }