
Tạo Script upload video lên Youtube bằng ChatGPT
Tạo Script upload video lên Youtube bằng ChatGPT
```
import os
import google.auth
import google.auth.exceptions
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
# Phạm vi cần thiết cho YouTube Data API
SCOPES = ['https://www.googleapis.com/auth/youtube.upload']
def upload_video_and_thumbnail(video_file, thumbnail_file, title, description, category_id, tags):
credentials = None
# Kiểm tra xem có token lưu trữ không
if os.path.exists('token.json'):
credentials = Credentials.from_authorized_user_file('token.json', SCOPES)
# Nếu không có hoặc token hết hạn, thực hiện đăng nhập OAuth2
if not credentials or not credentials.valid:
if credentials and credentials.expired and credentials.refresh_token:
credentials.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('client_secret_3_9_2024.json', SCOPES)
credentials = flow.run_local_server(port=0)
# Lưu trữ token để lần sau sử dụng
with open('token.json', 'w') as token:
token.write(credentials.to_json())
# Khởi tạo YouTube API client
youtube = build('youtube', 'v3', credentials=credentials)
# Thiết lập metadata cho video
body = {
'snippet': {
'title': title,
'description': description,
'tags': tags,
'categoryId': category_id
},
'status': {
'privacyStatus': 'public'
}
}
# Upload video
media = MediaFileUpload(video_file, chunksize=-1, 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 video... {int(status.progress() * 100)}% complete")
print(f"Video upload complete! Video ID: {response['id']}")
# Upload thumbnail
if thumbnail_file:
request = youtube.thumbnails().set(
videoId=response['id'],
media_body=MediaFileUpload(thumbnail_file)
)
response = request.execute()
print("Thumbnail uploaded!")
if __name__ == '__main__':
upload_video_and_thumbnail(
video_file='o9Ng_StDTOs.mp4',
thumbnail_file='o9Ng_StDTOs_thumbnail.jpg',
title='Title Yen software testing 03-09',
description='Your Video Description',
category_id='22', # Category ID for 'People & Blogs'
tags=['tag1', 'tag2']
)
