shortbot / mirror.py
Pushp0120's picture
Update mirror.py
2459767 verified
Raw
History Blame Contribute Delete
3.01 kB
import sys
import os
import ssl
import pickle
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google.auth.transport.requests import Request
TOKEN_FILE = '/app/token.pickle'
VIDEO_PATH = '/app/mirror_video.mp4'
# Fix SSL issues globally
ssl._create_default_https_context = ssl._create_unverified_context
def get_credentials():
creds = None
if os.path.exists(TOKEN_FILE):
with open(TOKEN_FILE, 'rb') as f:
creds = pickle.load(f)
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
with open(TOKEN_FILE, 'wb') as f:
pickle.dump(creds, f)
return creds
def download_from_youtube(video_id, output_path):
from pytubefix import YouTube
from pytubefix.cli import on_progress
url = f"https://www.youtube.com/watch?v={video_id}"
print(f"Downloading: {url}")
if os.path.exists(output_path):
os.remove(output_path)
yt = YouTube(url, on_progress_callback=on_progress, use_oauth=False, allow_oauth_cache=False)
print(f"Title: {yt.title}")
# Get highest resolution progressive stream (audio+video together)
stream = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').last()
if not stream:
# Fallback to any mp4
stream = yt.streams.filter(file_extension='mp4').first()
if not stream:
raise Exception("No suitable stream found!")
print(f"Downloading stream: {stream.resolution} {stream.mime_type}")
stream.download(filename=output_path)
print("Download complete!")
def upload_to_channel_b(title, description):
creds = get_credentials()
youtube = build('youtube', 'v3', credentials=creds)
body = {
'snippet': {
'title': title,
'description': description,
'categoryId': '22',
'tags': ['shorts', 'viral', 'trending']
},
'status': {
'privacyStatus': 'public',
'selfDeclaredMadeForKids': False
}
}
media = MediaFileUpload(VIDEO_PATH, mimetype='video/mp4', resumable=True)
request = youtube.videos().insert(part='snippet,status', body=body, media_body=media)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print(f"Uploading... {int(status.progress() * 100)}%")
new_id = response['id']
print(f"Uploaded! New Video ID: {new_id}")
if os.path.exists(VIDEO_PATH):
os.remove(VIDEO_PATH)
return new_id
if __name__ == '__main__':
video_id = sys.argv[1]
title = sys.argv[2] if len(sys.argv) > 2 else 'Mirrored Video'
description = sys.argv[3] if len(sys.argv) > 3 else ''
try:
download_from_youtube(video_id, VIDEO_PATH)
new_video_id = upload_to_channel_b(title, description)
print(f"SUCCESS:{new_video_id}")
except Exception as e:
print(f"FAILED: {e}")
sys.exit(1)