mirror of
https://github.com/Alvin-Zilverstand/Twitter-X-Media-Batch-Downloader.git
synced 2026-11-24 15:23:11 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
affd36c968 | ||
|
|
281ea82656 | ||
|
|
aa003fab4c | ||
|
|
805fade0fb | ||
|
|
dacf6f5a01 | ||
|
|
fe095afb38 | ||
|
|
e769ea8d20 | ||
|
|
befe838e79 | ||
|
|
b534bc278e | ||
|
|
2e882635eb | ||
|
|
5d5b778c8e | ||
|
|
7cf134f681 | ||
|
|
7d90eb7cb2 | ||
|
|
3d1fd7d1fb | ||
|
|
c0885b1812 | ||
|
|
1ca5c613ae | ||
|
|
596ba9bb3c | ||
|
|
a1cbb04402 | ||
|
|
ddf6439893 | ||
|
|
fed2bf7b0c | ||
|
|
241884de89 | ||
|
|
77b443ace0 | ||
|
|
cd48b6f9bc | ||
|
|
6f45b48047 | ||
|
|
7083c56c8b | ||
|
|
60cb3cbabd | ||
|
|
b38bff238a | ||
|
|
d4d216ed6b | ||
|
|
129c007f6f | ||
|
|
d78ad32c09 | ||
|
|
3975e5dd0e | ||
|
|
37f1d910cb | ||
|
|
74ed38cc31 | ||
|
|
2e326c39a0 | ||
|
|
39c37d4776 | ||
|
|
5709d76ceb | ||
|
|
75b3549653 | ||
|
|
ebe739e612 | ||
|
|
d423f20bad | ||
|
|
fba8a8ac45 | ||
|
|
a36c7613d2 | ||
|
|
c7615ed2f6 | ||
|
|
0c17f1b419 | ||
|
|
dd38880366 | ||
|
|
306d2c3c95 | ||
|
|
1caa59bbcf | ||
|
|
4d0021092c | ||
|
|
981bc8d9ec | ||
|
|
c894bfd4d2 | ||
|
|
61e50b8121 | ||
|
|
ba69dd7cf4 | ||
|
|
bcc332d0d7 | ||
|
|
82184aef33 | ||
|
|
357ad0f020 | ||
|
|
43f4d84593 | ||
|
|
4cecb6b14e | ||
|
|
eb712d5d8d | ||
|
|
46c178fec0 | ||
|
|
8ce5f1f833 | ||
|
|
0a80a3d331 | ||
|
|
f8b27ecb5a | ||
|
|
70e79af700 | ||
|
|
4fb60840a0 | ||
|
|
5613c152f8 | ||
|
|
ad5d7727eb | ||
|
|
ed1f0fce06 | ||
|
|
ee92174773 | ||
|
|
f08ce57feb | ||
|
|
4f21321e42 | ||
|
|
c8b7a5365a | ||
|
|
1049b544c5 | ||
|
|
e7db97a936 | ||
|
|
af1280b798 | ||
|
|
4f6004a501 | ||
|
|
e7141cd8d1 | ||
|
|
4d6f4d904a | ||
|
|
4081e6aacf | ||
|
|
2b405a16a7 | ||
|
|
5e658c05d4 | ||
|
|
b26dd0b2af | ||
|
|
28422dcf1d | ||
|
|
46e09532fc | ||
|
|
967d91d370 | ||
|
|
2ff0242e32 | ||
|
|
1e1d612807 | ||
|
|
9821dd8c65 | ||
|
|
46bb7d38f7 | ||
|
|
112f5992c4 | ||
|
|
178b3c490f | ||
|
|
bb1c0dccae | ||
|
|
0cf5316745 | ||
|
|
c3493944e8 | ||
|
|
c656459171 | ||
|
|
0e14f92244 | ||
|
|
fad4434753 | ||
|
|
77a9c83f4d | ||
|
|
7fa277931c | ||
|
|
be080481bf | ||
|
|
8a720e3e2b | ||
|
|
48a672e0bd | ||
|
|
91210f1c82 | ||
|
|
cb2a244e37 | ||
|
|
096425a0e1 | ||
|
|
c01a995b3d | ||
|
|
b28b4ef14c | ||
|
|
1e14fa6934 | ||
|
|
eac8a0f168 | ||
|
|
f3904c276c | ||
|
|
fe9724fa2f | ||
|
|
85e8f3135a | ||
|
|
1e2725f900 | ||
|
|
8e114a45e0 | ||
|
|
92267dbf5e | ||
|
|
37da356f4c | ||
|
|
eb268f5f9f | ||
|
|
e8ac4b8734 | ||
|
|
99afe59a11 | ||
|
|
8e8c0667df | ||
|
|
03479326b3 | ||
|
|
b39f40e9f9 | ||
|
|
5ed127f226 | ||
|
|
3487edf691 | ||
|
|
5b336df1d4 | ||
|
|
dfb536f663 | ||
|
|
2b5e7985d5 | ||
|
|
81bacad4d8 | ||
|
|
aa89fda847 | ||
|
|
e98cd51cf4 | ||
|
|
6bb5348485 | ||
|
|
784bb494fc | ||
|
|
5096e18cb8 | ||
|
|
2237de2b2c | ||
|
|
4656ebc56c | ||
|
|
f5357370b1 | ||
|
|
e216769e57 | ||
|
|
72fb45fc8a | ||
|
|
f6a2986dbf | ||
|
|
20b15191ac | ||
|
|
c616d688ff | ||
|
|
3f35f81fbe | ||
|
|
9109eeca76 | ||
|
|
d70b0c3522 | ||
|
|
e324d7b724 |
No files matched your search
@@ -1,75 +0,0 @@
|
|||||||
import json
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import os
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
def get_metadata(username):
|
|
||||||
if sys.platform == 'win32':
|
|
||||||
sys.stdout.reconfigure(encoding='utf-8')
|
|
||||||
|
|
||||||
url = f"https://x.com/{username}/timeline"
|
|
||||||
|
|
||||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
|
|
||||||
cookies_path = os.path.join(current_dir, 'cookies.json')
|
|
||||||
output_path = os.path.join(current_dir, f'{username}.json')
|
|
||||||
gallery_dl_path = os.path.join(current_dir, 'gallery-dl.exe')
|
|
||||||
|
|
||||||
config = {
|
|
||||||
"extractor": {
|
|
||||||
"twitter": {
|
|
||||||
"cookies": {
|
|
||||||
"auth_token": ""
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
with open(cookies_path, 'w') as f:
|
|
||||||
json.dump(config, f)
|
|
||||||
|
|
||||||
result = subprocess.run([gallery_dl_path, '-j', '--config', cookies_path, url],
|
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
encoding='utf-8',
|
|
||||||
check=True)
|
|
||||||
|
|
||||||
os.remove(cookies_path)
|
|
||||||
|
|
||||||
data = json.loads(result.stdout)
|
|
||||||
output = {
|
|
||||||
'account_info': {},
|
|
||||||
'timeline': []
|
|
||||||
}
|
|
||||||
|
|
||||||
for item in data:
|
|
||||||
if isinstance(item, list) and len(item) > 2 and isinstance(item[2], dict):
|
|
||||||
if not output['account_info'] and 'user' in item[2]:
|
|
||||||
user = item[2]['user']
|
|
||||||
output['account_info'] = {
|
|
||||||
'date': user.get('date', ''),
|
|
||||||
'followers_count': user.get('followers_count', ''),
|
|
||||||
'friends_count': user.get('friends_count', ''),
|
|
||||||
'name': user.get('name', ''),
|
|
||||||
'nick': user.get('nick', ''),
|
|
||||||
'profile_image': user.get('profile_image', ''),
|
|
||||||
'statuses_count': user.get('statuses_count', '')
|
|
||||||
}
|
|
||||||
if isinstance(item[1], str):
|
|
||||||
url = item[1]
|
|
||||||
if ('pbs.twimg.com' in url and 'format=jpg&name=orig' in url) or 'video.twimg.com' in url:
|
|
||||||
tweet_date = item[2].get('date')
|
|
||||||
if not tweet_date:
|
|
||||||
tweet_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
||||||
|
|
||||||
output['timeline'].append({
|
|
||||||
'url': url,
|
|
||||||
'date': tweet_date
|
|
||||||
})
|
|
||||||
|
|
||||||
with open(output_path, 'w', encoding='utf-8') as f:
|
|
||||||
json.dump(output, f, ensure_ascii=False, indent=2)
|
|
||||||
|
|
||||||
username = ""
|
|
||||||
get_metadata(username)
|
|
||||||
Binary file not shown.
@@ -1,25 +1,70 @@
|
|||||||
[](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases)
|
[](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases)
|
||||||
|
|
||||||
**Twitter/X Media Batch Downloader** is a GUI tool for downloading all media, including images and videos, from Twitter/X accounts, using `gallery-dl` and requiring `cookies.`
|

|
||||||
|
|
||||||
## Download
|
<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 using <code>gallery-dl</code>
|
||||||
|
</div>
|
||||||
|
|
||||||
## Screenshots
|
## 📥 Download
|
||||||
|
|
||||||

|
- [**Windows**](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v3.5/TwitterXMediaBatchDownloader_Windows.exe)
|
||||||
|
- [**Linux**](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v3.5/TwitterXMediaBatchDownloader_Linux)
|
||||||
|
- [**Mac**](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v3.5/TwitterXMediaBatchDownloader_Mac.app.zip)
|
||||||
|
- If you're familiar with **userscripts**, please install it [**here**](https://greasyfork.org/en/scripts/523157)
|
||||||
|
|
||||||

|
## ✨ Features
|
||||||
|
|
||||||

|
- Powered by `gallery-dl`, similar to `yt-dlp`
|
||||||
|
- **Bulk fetch**: Fetch multiple accounts at once
|
||||||
|
- **Bulk download**: Download multiple accounts at once
|
||||||
|
- Media-type selection: All (Images + GIFs + Videos) or specific (Images / GIFs / Videos)
|
||||||
|
- **MP4 → GIF conversion:** Convert downloaded MP4 videos into GIF format
|
||||||
|
- Downloads at original quality
|
||||||
|
|
||||||
## How to obtain Auth Token
|
## 🖼️ Screenshots
|
||||||
|
|
||||||
1. Go to [X's website](https://www.x.com/)
|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
### The downloaded application won't run❓
|
||||||
|
|
||||||
|
🐧 **Solution (Ubuntu/Linux)**: Open your terminal and run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
chmod +x TwitterXMediaBatchDownloader_Linux
|
||||||
|
```
|
||||||
|
https://github.com/user-attachments/assets/cc7400ec-76dd-4519-848d-71a834b7ec95
|
||||||
|
|
||||||
|
🍎 **Solution (macOS)**: Open your terminal and run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
xattr -rd com.apple.quarantine ~/Downloads/TwitterXMediaBatchDownloader_Mac.app
|
||||||
|
```
|
||||||
|
https://github.com/user-attachments/assets/4b13c0b9-cf3a-48ce-ac35-a19007189ac8
|
||||||
|
|
||||||
|
## 🔑 How to Obtain Auth Token
|
||||||
|
|
||||||
|
> [!Warning]
|
||||||
|
> - I suggest not using the **main account** to obtain the token.
|
||||||
|
> - 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.**
|
||||||
|
> - If too many media files are fetched, it may trigger a **rate limit**, and the media retrieval will fail, try enabling Batch mode.
|
||||||
|
|
||||||
|
### [Video Tutorial](https://www.patreon.com/posts/how-to-obtain-127206894)
|
||||||
|
|
||||||
|
1. Go to [Twitter's website](https://www.x.com/)
|
||||||
2. Log into your account
|
2. Log into your account
|
||||||
3. Open the Developer Tools by pressing `F12`
|
3. Open the Developer Tools by pressing `F12`
|
||||||
4. Navigate to the **Application** tab, then select **Storage** > **Cookies**
|
4. Navigate to the **Application** tab, then select **Storage → Cookies**
|
||||||
5. Find and copy the `auth_token` value
|
5. Find and copy the `auth_token` value or use the browser extension [X.com Auth Token Grabber](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v1.0/X.com.Auth.Token.Grabber.zip)
|
||||||
6. Do not log out of your account, as a new `auth_token` will be generated by Twitter
|
6. Do not log out of your account, as a new `auth_token` will be generated by Twitter
|
||||||
7. Close your browser
|
|
||||||
|
|
||||||

|
> X.com Auth Token Grabber
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
> Developer Tools
|
||||||
|
|
||||||
|

|
||||||
@@ -1,676 +0,0 @@
|
|||||||
import sys
|
|
||||||
import os
|
|
||||||
import json
|
|
||||||
import asyncio
|
|
||||||
import aiohttp
|
|
||||||
import subprocess
|
|
||||||
from datetime import datetime
|
|
||||||
from pathlib import Path
|
|
||||||
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
|
|
||||||
QHBoxLayout, QLabel, QLineEdit, QPushButton,
|
|
||||||
QProgressBar, QFileDialog, QRadioButton, QComboBox)
|
|
||||||
from PyQt6.QtCore import QThread, pyqtSignal, Qt, QSettings
|
|
||||||
from PyQt6.QtGui import QIcon, QPixmap, QCursor
|
|
||||||
|
|
||||||
class ImageDownloader(QThread):
|
|
||||||
finished = pyqtSignal(bytes)
|
|
||||||
|
|
||||||
def __init__(self, url):
|
|
||||||
super().__init__()
|
|
||||||
self.url = url
|
|
||||||
|
|
||||||
async def download_image(self):
|
|
||||||
async with aiohttp.ClientSession() as session:
|
|
||||||
async with session.get(self.url) as response:
|
|
||||||
if response.status == 200:
|
|
||||||
return await response.read()
|
|
||||||
return None
|
|
||||||
|
|
||||||
def run(self):
|
|
||||||
image_data = asyncio.run(self.download_image())
|
|
||||||
if image_data:
|
|
||||||
self.finished.emit(image_data)
|
|
||||||
|
|
||||||
class MetadataFetcher(QThread):
|
|
||||||
finished = pyqtSignal(dict)
|
|
||||||
error = pyqtSignal(str)
|
|
||||||
|
|
||||||
def __init__(self, username):
|
|
||||||
super().__init__()
|
|
||||||
self.username = username
|
|
||||||
|
|
||||||
def run(self):
|
|
||||||
try:
|
|
||||||
username = self.username.strip()
|
|
||||||
if "x.com/" in username or "twitter.com/" in username:
|
|
||||||
username = username.split("/")[-1]
|
|
||||||
if username.endswith("/timeline"):
|
|
||||||
username = username[:-9]
|
|
||||||
|
|
||||||
url = f"https://x.com/{username}/timeline"
|
|
||||||
|
|
||||||
if getattr(sys, 'frozen', False):
|
|
||||||
base_path = sys._MEIPASS
|
|
||||||
else:
|
|
||||||
base_path = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
|
|
||||||
cookies_path = os.path.join(base_path, 'cookies.json')
|
|
||||||
gallery_dl_path = os.path.join(base_path, 'gallery-dl.exe')
|
|
||||||
|
|
||||||
if not os.path.exists(gallery_dl_path):
|
|
||||||
gallery_dl_path = os.path.join(os.getcwd(), 'gallery-dl.exe')
|
|
||||||
|
|
||||||
if not os.path.exists(gallery_dl_path):
|
|
||||||
gallery_dl_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'gallery-dl.exe')
|
|
||||||
|
|
||||||
if not os.path.exists(gallery_dl_path):
|
|
||||||
raise FileNotFoundError(
|
|
||||||
"gallery-dl.exe not found. Please ensure it's in the same directory as the executable."
|
|
||||||
)
|
|
||||||
|
|
||||||
config = {
|
|
||||||
"extractor": {
|
|
||||||
"twitter": {
|
|
||||||
"cookies": {
|
|
||||||
"auth_token": self.auth_token
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try:
|
|
||||||
cookies_dir = os.path.dirname(cookies_path)
|
|
||||||
if not os.path.exists(cookies_dir):
|
|
||||||
os.makedirs(cookies_dir)
|
|
||||||
|
|
||||||
with open(cookies_path, 'w', encoding='utf-8') as f:
|
|
||||||
json.dump(config, f)
|
|
||||||
except Exception as e:
|
|
||||||
raise Exception(f"Failed to write cookies file: {str(e)}")
|
|
||||||
|
|
||||||
startupinfo = None
|
|
||||||
if sys.platform == 'win32':
|
|
||||||
startupinfo = subprocess.STARTUPINFO()
|
|
||||||
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
|
||||||
|
|
||||||
try:
|
|
||||||
process = subprocess.run(
|
|
||||||
[gallery_dl_path, '-j', '--config', cookies_path, url],
|
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
encoding='utf-8',
|
|
||||||
check=True,
|
|
||||||
startupinfo=startupinfo
|
|
||||||
)
|
|
||||||
except subprocess.CalledProcessError as e:
|
|
||||||
raise Exception(f"gallery-dl.exe failed: {e.stderr}")
|
|
||||||
except Exception as e:
|
|
||||||
raise Exception(f"Failed to execute gallery-dl.exe: {str(e)}")
|
|
||||||
finally:
|
|
||||||
try:
|
|
||||||
if os.path.exists(cookies_path):
|
|
||||||
os.remove(cookies_path)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
data = json.loads(process.stdout)
|
|
||||||
output = {
|
|
||||||
'account_info': {},
|
|
||||||
'timeline': []
|
|
||||||
}
|
|
||||||
|
|
||||||
for item in data:
|
|
||||||
if isinstance(item, list) and len(item) > 2 and isinstance(item[2], dict):
|
|
||||||
if not output['account_info'] and 'user' in item[2]:
|
|
||||||
user = item[2]['user']
|
|
||||||
output['account_info'] = {
|
|
||||||
'date': user.get('date', ''),
|
|
||||||
'followers_count': user.get('followers_count', ''),
|
|
||||||
'friends_count': user.get('friends_count', ''),
|
|
||||||
'name': user.get('name', ''),
|
|
||||||
'nick': user.get('nick', ''),
|
|
||||||
'profile_image': user.get('profile_image', ''),
|
|
||||||
'statuses_count': user.get('statuses_count', '')
|
|
||||||
}
|
|
||||||
if isinstance(item[1], str):
|
|
||||||
url = item[1]
|
|
||||||
if ('pbs.twimg.com' in url and 'format=jpg&name=orig' in url) or 'video.twimg.com' in url:
|
|
||||||
tweet_date = item[2].get('date')
|
|
||||||
if not tweet_date:
|
|
||||||
tweet_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
||||||
|
|
||||||
output['timeline'].append({
|
|
||||||
'url': url,
|
|
||||||
'date': tweet_date
|
|
||||||
})
|
|
||||||
|
|
||||||
self.finished.emit(output)
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
self.error.emit(str(e))
|
|
||||||
|
|
||||||
class MediaDownloader(QThread):
|
|
||||||
progress = pyqtSignal(int)
|
|
||||||
finished = pyqtSignal(str)
|
|
||||||
error = pyqtSignal(str)
|
|
||||||
status_update = pyqtSignal(str)
|
|
||||||
|
|
||||||
def __init__(self, media_list, output_dir, filename_format, username, batch_size=10):
|
|
||||||
super().__init__()
|
|
||||||
self.media_list = media_list
|
|
||||||
self.output_dir = output_dir
|
|
||||||
self.filename_format = filename_format
|
|
||||||
self.username = username
|
|
||||||
self.batch_size = batch_size
|
|
||||||
|
|
||||||
async def download_file(self, session, url, filepath):
|
|
||||||
try:
|
|
||||||
async with session.get(url) as response:
|
|
||||||
if response.status == 200:
|
|
||||||
with open(filepath, 'wb') as f:
|
|
||||||
f.write(await response.read())
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
|
|
||||||
async def download_all(self):
|
|
||||||
async with aiohttp.ClientSession() as session:
|
|
||||||
total = len(self.media_list)
|
|
||||||
completed = 0
|
|
||||||
|
|
||||||
tasks = []
|
|
||||||
for item in self.media_list:
|
|
||||||
url = item['url']
|
|
||||||
date = datetime.strptime(item['date'], "%Y-%m-%d %H:%M:%S")
|
|
||||||
formatted_date = date.strftime("%Y-%m-%d")
|
|
||||||
|
|
||||||
if self.filename_format == "username_date":
|
|
||||||
filename = f"{self.username}_{formatted_date}"
|
|
||||||
else:
|
|
||||||
filename = f"{formatted_date}_{self.username}"
|
|
||||||
|
|
||||||
filename = f"{filename}_{len(tasks):03d}.{'mp4' if 'video' in url else 'jpg'}"
|
|
||||||
|
|
||||||
filepath = os.path.join(self.output_dir, filename)
|
|
||||||
|
|
||||||
task = asyncio.create_task(self.download_file(session, url, filepath))
|
|
||||||
tasks.append(task)
|
|
||||||
|
|
||||||
if len(tasks) >= self.batch_size:
|
|
||||||
results = await asyncio.gather(*tasks)
|
|
||||||
completed += sum(1 for r in results if r)
|
|
||||||
progress = int((completed / total) * 100)
|
|
||||||
self.progress.emit(progress)
|
|
||||||
self.status_update.emit(f"Downloaded {completed} of {total} files...")
|
|
||||||
tasks = []
|
|
||||||
|
|
||||||
if tasks:
|
|
||||||
results = await asyncio.gather(*tasks)
|
|
||||||
completed += sum(1 for r in results if r)
|
|
||||||
progress = int((completed / total) * 100)
|
|
||||||
self.progress.emit(progress)
|
|
||||||
|
|
||||||
return completed
|
|
||||||
|
|
||||||
def run(self):
|
|
||||||
try:
|
|
||||||
completed = asyncio.run(self.download_all())
|
|
||||||
self.finished.emit(f"Downloaded {completed} files successfully!")
|
|
||||||
except Exception as e:
|
|
||||||
self.error.emit(str(e))
|
|
||||||
|
|
||||||
class TwitterMediaDownloaderGUI(QMainWindow):
|
|
||||||
def __init__(self):
|
|
||||||
super().__init__()
|
|
||||||
self.setWindowTitle("Twitter/X Media Batch Downloader")
|
|
||||||
|
|
||||||
icon_path = os.path.join(os.path.dirname(__file__), "icon.svg")
|
|
||||||
if os.path.exists(icon_path):
|
|
||||||
self.setWindowIcon(QIcon(icon_path))
|
|
||||||
|
|
||||||
self.setFixedWidth(600)
|
|
||||||
self.setFixedHeight(180)
|
|
||||||
|
|
||||||
self.default_pictures_dir = str(Path.home() / "Pictures")
|
|
||||||
if not os.path.exists(self.default_pictures_dir):
|
|
||||||
os.makedirs(self.default_pictures_dir)
|
|
||||||
|
|
||||||
self.media_info = None
|
|
||||||
self.settings = QSettings('TwitterMediaDownloader', 'Settings')
|
|
||||||
|
|
||||||
self.init_ui()
|
|
||||||
self.load_settings()
|
|
||||||
self.setup_auto_save()
|
|
||||||
|
|
||||||
def init_ui(self):
|
|
||||||
central_widget = QWidget()
|
|
||||||
self.setCentralWidget(central_widget)
|
|
||||||
self.main_layout = QVBoxLayout(central_widget)
|
|
||||||
self.main_layout.setContentsMargins(10, 10, 10, 10)
|
|
||||||
|
|
||||||
self.input_widget = QWidget()
|
|
||||||
input_layout = QVBoxLayout(self.input_widget)
|
|
||||||
input_layout.setSpacing(10)
|
|
||||||
|
|
||||||
url_layout = QHBoxLayout()
|
|
||||||
url_label = QLabel("Username/URL:")
|
|
||||||
url_label.setFixedWidth(100)
|
|
||||||
|
|
||||||
self.url_input = QLineEdit()
|
|
||||||
self.url_input.setPlaceholderText("e.g. Takomayuyi or https://x.com/Takomayuyi")
|
|
||||||
self.url_input.setClearButtonEnabled(True)
|
|
||||||
|
|
||||||
self.fetch_button = QPushButton("Fetch")
|
|
||||||
self.fetch_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
|
||||||
self.fetch_button.setFixedWidth(100)
|
|
||||||
self.fetch_button.clicked.connect(self.fetch_metadata)
|
|
||||||
|
|
||||||
url_layout.addWidget(url_label)
|
|
||||||
url_layout.addWidget(self.url_input)
|
|
||||||
url_layout.addWidget(self.fetch_button)
|
|
||||||
input_layout.addLayout(url_layout)
|
|
||||||
|
|
||||||
dir_layout = QHBoxLayout()
|
|
||||||
dir_label = QLabel("Output Directory:")
|
|
||||||
dir_label.setFixedWidth(100)
|
|
||||||
|
|
||||||
self.dir_input = QLineEdit(self.default_pictures_dir)
|
|
||||||
|
|
||||||
self.dir_button = QPushButton("Browse")
|
|
||||||
self.dir_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
|
||||||
self.dir_button.setFixedWidth(100)
|
|
||||||
self.dir_button.clicked.connect(self.select_directory)
|
|
||||||
|
|
||||||
dir_layout.addWidget(dir_label)
|
|
||||||
dir_layout.addWidget(self.dir_input)
|
|
||||||
dir_layout.addWidget(self.dir_button)
|
|
||||||
input_layout.addLayout(dir_layout)
|
|
||||||
|
|
||||||
auth_layout = QHBoxLayout()
|
|
||||||
auth_label = QLabel("Auth Token:")
|
|
||||||
auth_label.setFixedWidth(100)
|
|
||||||
|
|
||||||
self.auth_input = QLineEdit()
|
|
||||||
self.auth_input.setPlaceholderText("Enter your Twitter/X auth_token")
|
|
||||||
self.auth_input.setClearButtonEnabled(True)
|
|
||||||
|
|
||||||
auth_layout.addWidget(auth_label)
|
|
||||||
auth_layout.addWidget(self.auth_input)
|
|
||||||
input_layout.addLayout(auth_layout)
|
|
||||||
|
|
||||||
combined_layout = QHBoxLayout()
|
|
||||||
|
|
||||||
batch_label = QLabel("Batch Size:")
|
|
||||||
batch_label.setFixedWidth(100)
|
|
||||||
|
|
||||||
self.batch_size_combo = QComboBox()
|
|
||||||
self.batch_size_combo.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
|
||||||
self.batch_size_combo.setFixedWidth(70)
|
|
||||||
for size in range(10, 101, 10):
|
|
||||||
self.batch_size_combo.addItem(str(size))
|
|
||||||
|
|
||||||
format_label = QLabel("Filename:")
|
|
||||||
format_label.setFixedWidth(50)
|
|
||||||
|
|
||||||
self.format_username_date = QRadioButton("Username - Date")
|
|
||||||
self.format_date_username = QRadioButton("Date - Username")
|
|
||||||
self.format_username_date.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
|
||||||
self.format_date_username.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
|
||||||
|
|
||||||
combined_layout.addWidget(batch_label)
|
|
||||||
combined_layout.addWidget(self.batch_size_combo)
|
|
||||||
combined_layout.addSpacing(10)
|
|
||||||
combined_layout.addWidget(format_label)
|
|
||||||
combined_layout.addWidget(self.format_username_date)
|
|
||||||
combined_layout.addWidget(self.format_date_username)
|
|
||||||
combined_layout.addStretch()
|
|
||||||
|
|
||||||
input_layout.addLayout(combined_layout)
|
|
||||||
|
|
||||||
self.main_layout.addWidget(self.input_widget)
|
|
||||||
|
|
||||||
self.profile_widget = QWidget()
|
|
||||||
self.profile_widget.hide()
|
|
||||||
profile_layout = QHBoxLayout(self.profile_widget)
|
|
||||||
profile_layout.setContentsMargins(0, 0, 0, 0)
|
|
||||||
profile_layout.setSpacing(10)
|
|
||||||
|
|
||||||
profile_container = QWidget()
|
|
||||||
profile_image_layout = QVBoxLayout(profile_container)
|
|
||||||
profile_image_layout.setContentsMargins(0, 0, 0, 0)
|
|
||||||
profile_image_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
|
|
||||||
|
|
||||||
self.profile_image_label = QLabel()
|
|
||||||
self.profile_image_label.setFixedSize(100, 100)
|
|
||||||
self.profile_image_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
|
||||||
profile_image_layout.addWidget(self.profile_image_label)
|
|
||||||
profile_layout.addWidget(profile_container)
|
|
||||||
|
|
||||||
profile_details_container = QWidget()
|
|
||||||
profile_details_layout = QVBoxLayout(profile_details_container)
|
|
||||||
profile_details_layout.setContentsMargins(0, 0, 0, 0)
|
|
||||||
profile_details_layout.setSpacing(2)
|
|
||||||
profile_details_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
|
|
||||||
|
|
||||||
self.name_label = QLabel()
|
|
||||||
self.name_label.setStyleSheet("font-size: 14px;")
|
|
||||||
self.name_label.setWordWrap(True)
|
|
||||||
self.name_label.setMinimumWidth(400)
|
|
||||||
|
|
||||||
self.join_date_label = QLabel()
|
|
||||||
self.join_date_label.setStyleSheet("font-size: 12px;")
|
|
||||||
self.join_date_label.setWordWrap(True)
|
|
||||||
self.join_date_label.setMinimumWidth(400)
|
|
||||||
|
|
||||||
self.followers_label = QLabel()
|
|
||||||
self.followers_label.setStyleSheet("font-size: 12px;")
|
|
||||||
self.followers_label.setWordWrap(True)
|
|
||||||
self.followers_label.setMinimumWidth(400)
|
|
||||||
|
|
||||||
self.following_label = QLabel()
|
|
||||||
self.following_label.setStyleSheet("font-size: 12px;")
|
|
||||||
self.following_label.setWordWrap(True)
|
|
||||||
self.following_label.setMinimumWidth(400)
|
|
||||||
|
|
||||||
self.posts_label = QLabel()
|
|
||||||
self.posts_label.setStyleSheet("font-size: 12px;")
|
|
||||||
self.posts_label.setWordWrap(True)
|
|
||||||
self.posts_label.setMinimumWidth(400)
|
|
||||||
|
|
||||||
profile_details_layout.addWidget(self.name_label)
|
|
||||||
profile_details_layout.addWidget(self.join_date_label)
|
|
||||||
profile_details_layout.addWidget(self.followers_label)
|
|
||||||
profile_details_layout.addWidget(self.following_label)
|
|
||||||
profile_details_layout.addWidget(self.posts_label)
|
|
||||||
profile_layout.addWidget(profile_details_container, stretch=1)
|
|
||||||
profile_layout.addStretch()
|
|
||||||
|
|
||||||
self.main_layout.addWidget(self.profile_widget)
|
|
||||||
|
|
||||||
self.download_button = QPushButton("Download")
|
|
||||||
self.download_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
|
||||||
self.download_button.setFixedWidth(100)
|
|
||||||
self.download_button.clicked.connect(self.start_download)
|
|
||||||
self.download_button.hide()
|
|
||||||
|
|
||||||
self.cancel_button = QPushButton("Cancel")
|
|
||||||
self.cancel_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
|
||||||
self.cancel_button.setFixedWidth(100)
|
|
||||||
self.cancel_button.clicked.connect(self.cancel_clicked)
|
|
||||||
self.cancel_button.hide()
|
|
||||||
|
|
||||||
self.open_button = QPushButton("Open")
|
|
||||||
self.open_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
|
||||||
self.open_button.setFixedWidth(100)
|
|
||||||
self.open_button.clicked.connect(self.open_output_directory)
|
|
||||||
self.open_button.hide()
|
|
||||||
|
|
||||||
button_layout = QHBoxLayout()
|
|
||||||
button_layout.addStretch()
|
|
||||||
button_layout.addWidget(self.open_button)
|
|
||||||
button_layout.addWidget(self.download_button)
|
|
||||||
button_layout.addWidget(self.cancel_button)
|
|
||||||
button_layout.addStretch()
|
|
||||||
self.main_layout.addLayout(button_layout)
|
|
||||||
|
|
||||||
self.progress_bar = QProgressBar()
|
|
||||||
self.progress_bar.hide()
|
|
||||||
self.main_layout.addWidget(self.progress_bar)
|
|
||||||
|
|
||||||
bottom_layout = QHBoxLayout()
|
|
||||||
|
|
||||||
self.status_label = QLabel("")
|
|
||||||
bottom_layout.addWidget(self.status_label, stretch=1)
|
|
||||||
|
|
||||||
self.update_button = QPushButton()
|
|
||||||
icon_path = os.path.join(os.path.dirname(__file__), "update.svg")
|
|
||||||
if os.path.exists(icon_path):
|
|
||||||
self.update_button.setIcon(QIcon(icon_path))
|
|
||||||
self.update_button.setFixedSize(16, 16)
|
|
||||||
self.update_button.setStyleSheet("""
|
|
||||||
QPushButton {
|
|
||||||
border: none;
|
|
||||||
background: transparent;
|
|
||||||
}
|
|
||||||
QPushButton:hover {
|
|
||||||
background: transparent;
|
|
||||||
}
|
|
||||||
""")
|
|
||||||
self.update_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
|
||||||
self.update_button.setToolTip("Check for Updates")
|
|
||||||
self.update_button.clicked.connect(self.open_update_page)
|
|
||||||
|
|
||||||
bottom_layout.addWidget(self.update_button)
|
|
||||||
|
|
||||||
self.main_layout.addLayout(bottom_layout)
|
|
||||||
|
|
||||||
def open_update_page(self):
|
|
||||||
import webbrowser
|
|
||||||
webbrowser.open('https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases')
|
|
||||||
|
|
||||||
def setup_auto_save(self):
|
|
||||||
self.url_input.textChanged.connect(self.auto_save_settings)
|
|
||||||
self.auth_input.textChanged.connect(self.auto_save_settings)
|
|
||||||
self.dir_input.textChanged.connect(self.auto_save_settings)
|
|
||||||
self.format_username_date.toggled.connect(self.auto_save_settings)
|
|
||||||
self.batch_size_combo.currentTextChanged.connect(self.auto_save_settings)
|
|
||||||
|
|
||||||
def auto_save_settings(self):
|
|
||||||
self.settings.setValue('url_input', self.url_input.text())
|
|
||||||
self.settings.setValue('auth_token', self.auth_input.text())
|
|
||||||
self.settings.setValue('output_dir', self.dir_input.text())
|
|
||||||
self.settings.setValue('filename_format',
|
|
||||||
'username_date' if self.format_username_date.isChecked() else 'date_username')
|
|
||||||
self.settings.setValue('batch_size', self.batch_size_combo.currentText())
|
|
||||||
self.settings.sync()
|
|
||||||
|
|
||||||
def load_settings(self):
|
|
||||||
self.url_input.setText(self.settings.value('url_input', '', str))
|
|
||||||
self.auth_input.setText(self.settings.value('auth_token', '', str))
|
|
||||||
self.dir_input.setText(self.settings.value('output_dir', self.default_pictures_dir, str))
|
|
||||||
|
|
||||||
format_setting = self.settings.value('filename_format', 'username_date')
|
|
||||||
self.format_username_date.setChecked(format_setting == 'username_date')
|
|
||||||
self.format_date_username.setChecked(format_setting == 'date_username')
|
|
||||||
|
|
||||||
batch_size = self.settings.value('batch_size', '10')
|
|
||||||
index = self.batch_size_combo.findText(batch_size)
|
|
||||||
if index >= 0:
|
|
||||||
self.batch_size_combo.setCurrentIndex(index)
|
|
||||||
|
|
||||||
def select_directory(self):
|
|
||||||
directory = QFileDialog.getExistingDirectory(self, "Select Output Directory")
|
|
||||||
if directory:
|
|
||||||
self.dir_input.setText(directory)
|
|
||||||
|
|
||||||
def open_output_directory(self):
|
|
||||||
output_dir = self.dir_input.text().strip() or self.default_pictures_dir
|
|
||||||
if os.path.exists(output_dir):
|
|
||||||
if sys.platform == 'win32':
|
|
||||||
os.startfile(output_dir)
|
|
||||||
elif sys.platform == 'darwin':
|
|
||||||
subprocess.run(['open', output_dir])
|
|
||||||
else:
|
|
||||||
subprocess.run(['xdg-open', output_dir])
|
|
||||||
|
|
||||||
def fetch_metadata(self):
|
|
||||||
username = self.url_input.text().strip()
|
|
||||||
if not username:
|
|
||||||
self.status_label.setText("Please enter a username or URL")
|
|
||||||
return
|
|
||||||
|
|
||||||
auth_token = self.auth_input.text().strip()
|
|
||||||
if not auth_token:
|
|
||||||
self.status_label.setText("Please enter your auth token")
|
|
||||||
return
|
|
||||||
|
|
||||||
self.fetch_button.setEnabled(False)
|
|
||||||
self.status_label.setText("Fetching profile information...")
|
|
||||||
|
|
||||||
self.fetcher = MetadataFetcher(username)
|
|
||||||
self.fetcher.auth_token = auth_token
|
|
||||||
self.fetcher.finished.connect(self.handle_profile_info)
|
|
||||||
self.fetcher.error.connect(self.handle_fetch_error)
|
|
||||||
self.fetcher.start()
|
|
||||||
|
|
||||||
def handle_profile_info(self, info):
|
|
||||||
if not info.get('account_info'):
|
|
||||||
self.status_label.setText("Failed to fetch profile information")
|
|
||||||
self.fetch_button.setEnabled(True)
|
|
||||||
return
|
|
||||||
|
|
||||||
self.media_info = info
|
|
||||||
self.fetch_button.setEnabled(True)
|
|
||||||
|
|
||||||
account_info = info['account_info']
|
|
||||||
name = account_info['name']
|
|
||||||
nick = account_info['nick']
|
|
||||||
join_date = datetime.strptime(account_info['date'], "%Y-%m-%d %H:%M:%S")
|
|
||||||
followers = account_info['followers_count']
|
|
||||||
following = account_info['friends_count']
|
|
||||||
posts = account_info['statuses_count']
|
|
||||||
|
|
||||||
join_date_str = join_date.strftime("%A, %d %B %Y - %H:%M")
|
|
||||||
|
|
||||||
self.name_label.setText(f"<b>{name}</b> ({nick})")
|
|
||||||
self.join_date_label.setText(f"<b>Join Date:</b> {join_date_str}")
|
|
||||||
self.followers_label.setText(f"<b>Followers:</b> {followers:,}")
|
|
||||||
self.following_label.setText(f"<b>Following:</b> {following:,}")
|
|
||||||
self.posts_label.setText(f"<b>Posts:</b> {posts:,}")
|
|
||||||
|
|
||||||
media_count = len(info['timeline'])
|
|
||||||
self.status_label.setText(f"Successfully fetched {media_count:,} media items")
|
|
||||||
|
|
||||||
profile_image_url = account_info['profile_image']
|
|
||||||
self.image_downloader = ImageDownloader(profile_image_url)
|
|
||||||
self.image_downloader.finished.connect(self.update_profile_image)
|
|
||||||
self.image_downloader.start()
|
|
||||||
|
|
||||||
self.input_widget.hide()
|
|
||||||
self.profile_widget.show()
|
|
||||||
self.download_button.show()
|
|
||||||
self.cancel_button.show()
|
|
||||||
self.update_button.hide()
|
|
||||||
|
|
||||||
username = self.url_input.text().strip()
|
|
||||||
if "x.com/" in username or "twitter.com/" in username:
|
|
||||||
username = username.split("/")[-1]
|
|
||||||
if username.endswith("/timeline"):
|
|
||||||
username = username[:-9]
|
|
||||||
|
|
||||||
output_base = self.dir_input.text().strip() or self.default_pictures_dir
|
|
||||||
self.user_output_dir = os.path.join(output_base, username)
|
|
||||||
if not os.path.exists(self.user_output_dir):
|
|
||||||
os.makedirs(self.user_output_dir)
|
|
||||||
|
|
||||||
def update_profile_image(self, image_data):
|
|
||||||
pixmap = QPixmap()
|
|
||||||
pixmap.loadFromData(image_data)
|
|
||||||
scaled_pixmap = pixmap.scaled(100, 100, Qt.AspectRatioMode.KeepAspectRatio,
|
|
||||||
Qt.TransformationMode.SmoothTransformation)
|
|
||||||
self.profile_image_label.setPixmap(scaled_pixmap)
|
|
||||||
|
|
||||||
def handle_fetch_error(self, error):
|
|
||||||
self.fetch_button.setEnabled(True)
|
|
||||||
self.status_label.setText(f"Error fetching profile info: {error}")
|
|
||||||
|
|
||||||
def start_download(self):
|
|
||||||
if not self.media_info:
|
|
||||||
self.status_label.setText("Please fetch profile information first")
|
|
||||||
return
|
|
||||||
|
|
||||||
auth_token = self.auth_input.text().strip()
|
|
||||||
if not auth_token:
|
|
||||||
self.status_label.setText("Please enter your auth token")
|
|
||||||
return
|
|
||||||
|
|
||||||
self.download_button.hide()
|
|
||||||
self.cancel_button.hide()
|
|
||||||
self.progress_bar.show()
|
|
||||||
self.progress_bar.setValue(0)
|
|
||||||
self.status_label.setText("Starting download...")
|
|
||||||
|
|
||||||
filename_format = "username_date" if self.format_username_date.isChecked() else "date_username"
|
|
||||||
batch_size = int(self.batch_size_combo.currentText())
|
|
||||||
|
|
||||||
username = self.url_input.text().strip()
|
|
||||||
if "x.com/" in username or "twitter.com/" in username:
|
|
||||||
username = username.split("/")[-1]
|
|
||||||
if username.endswith("/timeline"):
|
|
||||||
username = username[:-9]
|
|
||||||
|
|
||||||
self.worker = MediaDownloader(
|
|
||||||
self.media_info['timeline'],
|
|
||||||
self.user_output_dir,
|
|
||||||
filename_format,
|
|
||||||
username,
|
|
||||||
batch_size
|
|
||||||
)
|
|
||||||
self.worker.progress.connect(self.update_progress)
|
|
||||||
self.worker.finished.connect(self.download_finished)
|
|
||||||
self.worker.error.connect(self.download_error)
|
|
||||||
self.worker.status_update.connect(self.status_label.setText)
|
|
||||||
self.worker.start()
|
|
||||||
|
|
||||||
def update_progress(self, value):
|
|
||||||
self.progress_bar.setValue(value)
|
|
||||||
|
|
||||||
def download_finished(self, message):
|
|
||||||
self.progress_bar.hide()
|
|
||||||
self.status_label.setText(message)
|
|
||||||
self.open_button.show()
|
|
||||||
self.download_button.setText("Clear")
|
|
||||||
self.download_button.clicked.disconnect()
|
|
||||||
self.download_button.clicked.connect(self.clear_form)
|
|
||||||
self.download_button.show()
|
|
||||||
self.cancel_button.hide()
|
|
||||||
|
|
||||||
def clear_form(self):
|
|
||||||
self.url_input.clear()
|
|
||||||
self.profile_widget.hide()
|
|
||||||
self.input_widget.show()
|
|
||||||
self.download_button.hide()
|
|
||||||
self.cancel_button.hide()
|
|
||||||
self.open_button.hide()
|
|
||||||
self.progress_bar.hide()
|
|
||||||
self.progress_bar.setValue(0)
|
|
||||||
self.status_label.clear()
|
|
||||||
self.media_info = None
|
|
||||||
self.update_button.show()
|
|
||||||
self.fetch_button.setEnabled(True)
|
|
||||||
self.download_button.setText("Download")
|
|
||||||
self.download_button.clicked.disconnect()
|
|
||||||
self.download_button.clicked.connect(self.start_download)
|
|
||||||
|
|
||||||
def download_error(self, error_message):
|
|
||||||
self.progress_bar.hide()
|
|
||||||
self.status_label.setText(f"Download error: {error_message}")
|
|
||||||
self.download_button.setText("Retry")
|
|
||||||
self.download_button.show()
|
|
||||||
self.cancel_button.show()
|
|
||||||
|
|
||||||
def cancel_clicked(self):
|
|
||||||
self.profile_widget.hide()
|
|
||||||
self.input_widget.show()
|
|
||||||
self.download_button.hide()
|
|
||||||
self.cancel_button.hide()
|
|
||||||
self.open_button.hide()
|
|
||||||
self.progress_bar.hide()
|
|
||||||
self.progress_bar.setValue(0)
|
|
||||||
self.status_label.clear()
|
|
||||||
self.media_info = None
|
|
||||||
self.update_button.show()
|
|
||||||
self.fetch_button.setEnabled(True)
|
|
||||||
|
|
||||||
def main():
|
|
||||||
if getattr(sys, 'frozen', False):
|
|
||||||
os.chdir(os.path.dirname(sys.executable))
|
|
||||||
|
|
||||||
app = QApplication(sys.argv)
|
|
||||||
window = TwitterMediaDownloaderGUI()
|
|
||||||
window.show()
|
|
||||||
sys.exit(app.exec())
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+186
@@ -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": "To download withheld accounts, use this userscript version: https://www.patreon.com/exyezed"}
|
||||||
|
else:
|
||||||
|
error_str = str(e)
|
||||||
|
if error_str == "None":
|
||||||
|
return {"error": "Failed to authenticate. Please verify your auth token is valid and not expired."}
|
||||||
|
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": "Failed to authenticate. Please verify your auth token is valid and not expired."}, ensure_ascii=False))
|
||||||
|
else:
|
||||||
|
print(json.dumps({"error": error_str}, ensure_ascii=False))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
PyQt6
|
||||||
|
requests
|
||||||
|
aiohttp
|
||||||
|
imageio-ffmpeg
|
||||||
|
packaging
|
||||||
|
gallery-dl
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"version": "3.5"
|
||||||
|
}
|
||||||
Reference in new issue
Block a user