copyright free image of youtube

Youtube automation + monetization. How to automate your earnings on youtube ?

By Imad Eddine Aris | justEducate | 30 Apr 2024


Hi, haven't you been thinking about starting a youtube channel but you didnt find exactly what content to share ?

welcome to the club, it happened to me too; the issue was that i'm too lazy to start a youtube channel because i couldn't find a niche that attracts my attention, but lately i got the idea to make youtube makes money for me while me doing nothing! yupe, nothing, only from single lines of code.

Let's not waste any time and get into it

LANGUAGE IS PYTHON

Youtube has the option called YouTube Data API, to integrate the api with your project you'll need to install library  google-api libraries 
then you will have to go to https://console.developers.google.com/ 

create a new project and enable API, then search for Youtube data api v3, after this you will need to create credintials to get thye api key, credintials button should be found on the sidebar.

this script allows you to interact with youtube directly through the official google api, the search_videos_by_query function allows you to perform searches based on filtering that you want such as video duration, language, and publication date. and most interesting part is the filter "CreativeCommon" this what lets you get unlicensed video and share them without any problem with copyrights. also the tool search video based on queries so you can add as many as you want or based on the content that you want to share e.g : gaming, sports, news....etc

Once the tool starts it returns a list of videos, the tool select a random video from the list, it downloads it with highest quality 

the most important part is uploading the video that the tool has downloaded, we use the same api from google console "youtube data api" but this time we use .insert command to upload the video to your channel.

 

i will share with you the complete code below, but im still developing it and here i will tell you what implementation you can add to the code for successful code.
- paraphrasing: you can use a paraphrasing library to paraphrase and modify the original title of the video.
- predefined description: you can use a predefined description for the video or you can create a list of descriptions and select each one based on the type of the video  e.g: gaming, sports, news
- predefined keywords or tags: you can use a predefined keywords or tags for the video or you can create a list of keywords or tags and select each one based on the type of the video  e.g: gaming, sports, news

- you can add a notification alert that sends you notifications about selected video before uploading it to choose whether uou want to upload or not (skip video)

- add a cron job that initialize the tool automatically, every 24 hours or 48 hours or more (more than 4 days is recommended)

HERE IS THE CODE:

import random
import os
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from datetime import datetime
from pytube import YouTube
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow


queries = ['video games', 'gaming industry', 'game development', 'online gaming']

def search_videos_by_query(query, api_key):
    try:
        youtube = build('youtube', 'v3', developerKey=api_key)

        start_date = datetime(2021, 1, 1).strftime('%Y-%m-%dT%H:%M:%SZ')
        end_date = datetime(2024, 12, 31).strftime('%Y-%m-%dT%H:%M:%SZ')

        request = youtube.search().list(
            part="snippet",
            maxResults=50, 
            q=query,
            type="video",
            videoDuration="long",
            relevanceLanguage="en", 
            videoLicense="creativeCommon",
            publishedAfter=start_date,
            publishedBefore=end_date 
        )

        response = request.execute()
        return response.get('items', [])
    except HttpError as e:
        print(f"An HTTP error occurred: {e}")
        return []

def get_video_url(video_id):
    return f"https://www.youtube.com/watch?v={video_id}"

def download_video(video_url):
    try:
        yt = YouTube(video_url)
        video = yt.streams.filter(progressive=True, file_extension='mp4').first()
        video.download()
        print("Video downloaded successfully.")
        return video.default_filename
    except Exception as e:
        print(f"An error occurred while downloading the video: {e}")
        return None

def authenticate_scopes():
    SCOPES = ['https://www.googleapis.com/auth/youtube.upload']
    creds = None
    if os.path.exists('token.json'):
        creds = google.auth.credentials.Credentials.from_authorized_user_file('token.json', SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    return creds

def upload_video(video_file, title, description):
    youtube = build('youtube', 'v3', credentials=authenticate_scopes())
    request = youtube.videos().insert(
        part="snippet,status",
        body={
          "snippet": {
            "categoryId": "20",
            "title": title,
            "description": description
          },
          "status": {
            "privacyStatus": "private"
          }
        },
        media_body=video_file
    )
    response = request.execute()
    print("Video uploaded successfully.")
    return response['id']

def main():
    api_key = 'YOUR_API_KEY'  # Set your Google API key

    query = random.choice(queries)

    videos = search_videos_by_query(query, api_key)

    if videos:
        video = random.choice(videos)
        title = video['snippet']['title']
        video_id = video['id']['videoId']
        video_url = get_video_url(video_id)
        print(f"Selected Video: {title}, Video ID: {video_id}, URL: {video_url}")

        video_filename = download_video(video_url)
        if video_filename:
            with open(video_filename, 'rb') as video_file:
                uploaded_video_id = upload_video(video_file, title, "Uploaded automatically from script.")
                print("Uploaded Video ID:", uploaded_video_id)
            os.remove(video_filename)
        else:
            print("Failed to download the video.")
    else:
        print("No videos found.")

if __name__ == "__main__":
    main()

 

How do you rate this article?

3


Imad Eddine Aris
Imad Eddine Aris

This is Imad, a Cybersecurity Analyst, Forex/Crypto trader and full stack developer.


justEducate
justEducate

Hello, this is my blog, in which we will address rich, useful and interesting topics on many interesting topics, the most important of which are 3 topics: 1: Cyber Security, 2: Forex/Crypto Trading, 3: programming and development. Additionally, there will be another category which is other topics (miscellaneous) Enjoy 👌😄

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.