I'm creating a tool to convert playlists between YouTube and Spotify, but the YouTube API has a problematic quota: each video costs 50 points (out of a daily total of 10,000), which is severely limiting my requests. Is there a way to add all the tracks in a list and add them all to the playlist in a single request?
import osimport googleapiclient.discoveryimport googleapiclient.errorsimport spotipyfrom spotipy.oauth2 import SpotifyClientCredentialsfrom google_auth_oauthlib.flow import InstalledAppFlowfrom secret.credentials import Credentialsfrom controller import getterfrom gui.colors import colored_text, ConsoleColors# Define the scopesSCOPES = ["https://www.googleapis.com/auth/youtube.force-ssl"]def extract_spotify_playlist_name(spotify_playlist_url): # Initialize Spotipy client client_credentials_manager = SpotifyClientCredentials(Credentials().get_id(), Credentials().get_secret()) sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) # Extract playlist ID from URL playlist_id = spotify_playlist_url.split('/')[-1] # Get playlist details playlist = sp.playlist(playlist_id) # Extract playlist name playlist_name = playlist['name'] return playlist_namedef create_youtube_playlist(spotify_playlist_url, youtube_playlist_name): # Define the scopes SCOPES = ["https://www.googleapis.com/auth/youtube"] # Load the credentials from json creds = None if os.path.exists('ytb_credentials/client_secret.json'): creds = InstalledAppFlow.from_client_secrets_file('ytb_credentials/client_secret.json', SCOPES).run_local_server(port=0) # Construa o serviço YouTube API usando as credenciais youtube = googleapiclient.discovery.build('youtube', 'v3', credentials=creds) # Create YouTube playlist try: request = youtube.playlists().insert( part="snippet,status", body={"snippet": {"title": youtube_playlist_name,"description": f"This playlist was created from {youtube_playlist_name} using BridgeBeats. For more, acess github.com/lilrau.","tags": ["BridgeBeats"] },"status": {"privacyStatus": "public" # Change this to "private" if you want a private playlist } } ) response = request.execute() playlist_id = response["id"] print(f"{colored_text('Playlist created successfully!', ConsoleColors.BACKGROUND_GREEN)} Playlist ID:", playlist_id) # Get tracks from Spotify playlist spotify_tracks = getter.get_spotify_tracks(spotify_playlist_url) # Add tracks to the YouTube playlist for track in spotify_tracks: try: # Search for the track on YouTube search_response = youtube.search().list( q=f"{track['artist']} - {track['name']}", part="id", maxResults=1 ).execute() # Add the first result to the playlist video_id = search_response["items"][0]["id"]["videoId"] youtube.playlistItems().insert( part="snippet", body={"snippet": {"playlistId": playlist_id,"position": 0,"resourceId": {"kind": "youtube#video","videoId": video_id } } } ).execute() print(f"Added {colored_text({track['artist']} - {track['name']}, ConsoleColors.GREEN)} to the playlist.") except Exception as e: print(f"{colored_text(f"Error adding {track['artist']} - {track['name']} to the playlist:", ConsoleColors.RED)}", e) except googleapiclient.errors.HttpError as e: print(f"{colored_text('An error occurred while creating the playlist:', ConsoleColors.RED)}", e) return
I found in the forum a batch processing solution, but I don't know how to use it, so GPT gave me this solution (of course did not worked):
def create_youtube_playlist(spotify_playlist_url, youtube_playlist_name): # Load the credentials from json creds = None if os.path.exists('ytb_credentials/client_secret.json'): creds = InstalledAppFlow.from_client_secrets_file('ytb_credentials/client_secret.json', SCOPES).run_local_server(port=0) # Build the YouTube API service youtube = googleapiclient.discovery.build('youtube', 'v3', credentials=creds) # Create YouTube playlist try: request = youtube.playlists().insert( part="snippet,status", body={"snippet": {"title": youtube_playlist_name,"description": f"This playlist was created from {youtube_playlist_name} using BridgeBeats. For more, acess github.com/lilrau.","tags": ["BridgeBeats"] },"status": {"privacyStatus": "public" # Change this to "private" if you want a private playlist } } ) response = request.execute() playlist_id = response["id"] print(f"{colored_text('Playlist created successfully!', ConsoleColors.BACKGROUND_GREEN)} Playlist ID:", playlist_id) # Get tracks from Spotify playlist spotify_tracks = getter.get_spotify_tracks(spotify_playlist_url) # Prepare batch requests batch = youtube.new_batch_http_request(callback=batch_callback) # Add tracks to the YouTube playlist for track in spotify_tracks: try: # Search for the track on YouTube search_response = youtube.search().list( q=f"{track['artist']} - {track['name']}", part="id", maxResults=1 ).execute() # Add the first result to the playlist video_id = search_response["items"][0]["id"]["videoId"] batch.add(youtube.playlistItems().insert( part="snippet", body={"snippet": {"playlistId": playlist_id,"position": 0,"resourceId": {"kind": "youtube#video","videoId": video_id } } } )) print(f"Added {colored_text({track['artist']} - {track['name']}, ConsoleColors.GREEN)} to the batch.") except Exception as e: print(f"{colored_text(f"Error adding {track['artist']} - {track['name']} to the batch:", ConsoleColors.RED)}", e) # Execute batch requests batch.execute() except googleapiclient.errors.HttpError as e: print(f"{colored_text('An error occurred while creating the playlist:', ConsoleColors.RED)}", e) returndef batch_callback(request_id, response, exception): if exception is not None: print(f"Request {request_id} failed: {exception}") else: print(f"Request {request_id} succeeded!")