February 20, 2024

YouTube Thumbnail changes with Python

Posted on February 20, 2024  •  5 minutes  • 939 words

YouTube thumbnails play a crucial role in attracting viewers and conveying the essence of your video.

Regularly updating your video thumbnails can enhance the visual appeal of your channel and encourage more clicks.

In this tutorial, we will explore how to automate YouTube thumbnail changes using a Python script.

Full video link: https://youtu.be/04qniyyFJt4

Prerequisites

Before diving into the scripting process, make sure you have the following:

1. Google API Key:

Generate an API key from the Google Cloud Console with access to the YouTube Data API.

2. Playlist ID:

Identify the YouTube playlist for which you want to update thumbnails.

3. Client Secrets File:

Obtain the application_default_credentials.json file to authenticate your script.

4. Create the thumbnails:

  1. Create all thumbnails for the playlist and rename all files as 1.png,2.png,…etc
  2. save all files in thumbs folder

Setting up the Python Script & Script Overview

1. Importing Required Libraries

The script starts by importing necessary libraries for handling authentication, API requests, and file operations.

import time
import os
import google.auth
import google.auth.transport.requests
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.oauth2.credentials import Credentials

2. Authentication

It authenticates the script using OAuth2 credentials. If token information is not available or is expired, the script prompts the user to log in.


def get_authenticated_service(client_secrets_file):
    # Set up OAuth2 credentials
    credentials = None
    if os.path.exists('token.json'):
        credentials = Credentials.from_authorized_user_file('token.json')

    # If credentials are not available or are invalid, let the user log in.
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            credentials.refresh(google.auth.transport.requests.Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                client_secrets_file, ['https://www.googleapis.com/auth/youtube.force-ssl']
            )
            credentials = flow.run_local_server(port=0)

        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(credentials.to_json())

    # Set up the YouTube API service
    youtube = build('youtube', 'v3', credentials=credentials)
    return youtube

3. YouTube API Service

The script sets up the YouTube API service using the authenticated credentials.


youtube_service = get_authenticated_service(CLIENT_SECRETS_FILE)

# Set the playlist ID for which you want to retrieve videos
playlist_id = PLAYLIST_ID

4. Retrieving Playlist Videos

It retrieves all videos from the specified playlist using the get_playlist_videos function.

def get_playlist_videos(youtube, playlist_id):
    # Retrieve all videos from the specified playlist
    playlist_items = []
    next_page_token = None

    while True:
        request = youtube.playlistItems().list(
            part='snippet',
            playlistId=playlist_id,
            maxResults=50,  # You can adjust this value based on your needs
            pageToken=next_page_token
        )
        response = request.execute()
        
        # Append videos to the list
        playlist_items.extend(response['items'])

        # Check for the next page
        next_page_token = response.get('nextPageToken')
        if not next_page_token:
            break

    return playlist_items

playlist_videos = get_playlist_videos(youtube_service, playlist_id)

5. Video Details

The script prints details of each video in the playlist, including video ID and title.


# Print video details
for video in playlist_videos:
    video_id = video['snippet']['resourceId']['videoId']
    video_title = video['snippet']['title']
    videoTitleToId[video_title] = video_id
    print(f"Video ID: {video_id}, Title: {video_title}")

6. Thumbnail Updates

For each video, the script identifies the corresponding thumbnail image and updates it using the set_video_thumbnail function.

def set_video_thumbnail(youtube, video_id, thumbnail_path):
    # Upload the thumbnail image
    request = youtube.thumbnails().set(
        videoId=video_id,
        media_body=thumbnail_path
    )
    response = request.execute()
    print(f'Thumbnail updated successfully:\n{response}')

for i in range(1,36):
    # Set the path to the new thumbnail image
    thumbnail_path = "thumbs/" + str(i) + ".png"
    video_id = ""
    video_title = ""
    for key in videoTitleToId.keys():
        if str(i) in str(key):
            video_title = key
            video_id = videoTitleToId[key]
    
    print(f"Video ID: {video_id}, thumbName: {thumbnail_path}, Title: {video_title}")

    # Set the video ID for which you want to change the thumbnail
    # Set the new thumbnail for the video
    set_video_thumbnail(youtube_service, video_id, thumbnail_path)
    time.sleep(10)

7. Running the Script

The main function calls all the necessary functions to execute the thumbnail update process.

python3 main.py

Full Code

Below is a Python script that automates YouTube thumbnail changes.

import time
import os
import google.auth
import google.auth.transport.requests
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.oauth2.credentials import Credentials

# Replace 'YOUR_API_KEY' with the API key you generated
API_KEY = ""

# Replace 'YOUR_PLAYLIST_ID' with the ID of the YouTube playlist
PLAYLIST_ID = 'PL9MpVynPwGzr_nBiH_jxWWzPo_kfcaD2n'

CLIENT_SECRETS_FILE = "application_default_credentials.json"

def get_authenticated_service(client_secrets_file):
    # Set up OAuth2 credentials
    credentials = None
    if os.path.exists('token.json'):
        credentials = Credentials.from_authorized_user_file('token.json')

    # If credentials are not available or are invalid, let the user log in.
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            credentials.refresh(google.auth.transport.requests.Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                client_secrets_file, ['https://www.googleapis.com/auth/youtube.force-ssl']
            )
            credentials = flow.run_local_server(port=0)

        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(credentials.to_json())

    # Set up the YouTube API service
    youtube = build('youtube', 'v3', credentials=credentials)
    return youtube

def get_playlist_videos(youtube, playlist_id):
    # Retrieve all videos from the specified playlist
    playlist_items = []
    next_page_token = None

    while True:
        request = youtube.playlistItems().list(
            part='snippet',
            playlistId=playlist_id,
            maxResults=50,  # You can adjust this value based on your needs
            pageToken=next_page_token
        )
        response = request.execute()
        
        # Append videos to the list
        playlist_items.extend(response['items'])

        # Check for the next page
        next_page_token = response.get('nextPageToken')
        if not next_page_token:
            break

    return playlist_items

def set_video_thumbnail(youtube, video_id, thumbnail_path):
    # Upload the thumbnail image
    request = youtube.thumbnails().set(
        videoId=video_id,
        media_body=thumbnail_path
    )
    response = request.execute()
    print(f'Thumbnail updated successfully:\n{response}')

def main():
    # Get the authenticated YouTube API service
    youtube_service = get_authenticated_service(CLIENT_SECRETS_FILE)

    # Set the playlist ID for which you want to retrieve videos
    playlist_id = PLAYLIST_ID

    # Get all videos from the playlist
    playlist_videos = get_playlist_videos(youtube_service, playlist_id)
    
    videoTitleToId = {}

    # Print video details
    for video in playlist_videos:
        video_id = video['snippet']['resourceId']['videoId']
        video_title = video['snippet']['title']
        videoTitleToId[video_title] = video_id
        print(f"Video ID: {video_id}, Title: {video_title}")
    
    for i in range(1,36):
        # Set the path to the new thumbnail image
        thumbnail_path = "thumbs/" + str(i) + ".png"
        video_id = ""
        video_title = ""
        for key in videoTitleToId.keys():
            if str(i) in str(key):
                video_title = key
                video_id = videoTitleToId[key]
        
        print(f"Video ID: {video_id}, thumbName: {thumbnail_path}, Title: {video_title}")

        # Set the video ID for which you want to change the thumbnail
        # Set the new thumbnail for the video
        set_video_thumbnail(youtube_service, video_id, thumbnail_path)
        time.sleep(10)
        

if __name__ == "__main__":
    main()
Follow me

I work on everything coding and share developer memes