0

I'm trying to get the video list of my youtube channel and update it as i please, i've done it with .net & it's quite easy, But in python it's kind of disturbing each time i run the script i got the message of "Please visit this URL to authorize this application" Althought i use the same credentials.json file i use it on .net.

NB: No need to mark down this question for duplicate or anything because i already check many Many of the same question here on stackover like this , this & this other forums too but none seems to provide a clear concrete solution every solution so far i've tried has the same result.

Here's the sample code i'm using :

Any help will be much appreciated.

import os
import sys
file_path = os.path.dirname(__file__)
module_path = os.path.join(file_path, "lib")
sys.path.append(module_path)
import pickle
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
scopes = [
    "https://www.googleapis.com/auth/youtube",
    "https://www.googleapis.com/auth/youtube.upload",
    "https://www.googleapis.com/auth/youtubepartner",
    "https://www.googleapis.com/auth/youtube.force-ssl",
    ]
client_secrets_file = "credentials.json"
api_service_name = "youtube"
api_version = "v3"

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    youtube = get_authenticated_service()
    request = youtube.channels().list(
        part="contentDetails",
        mine=True
    )
    response = request.execute()
    print(response)

def get_authenticated_service():
    if os.path.exists("CREDENTIALS_PICKLE_FILE"):
        with open("CREDENTIALS_PICKLE_FILE", 'rb') as f:
            credentials = pickle.load(f)
    else:
        flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(client_secrets_file, scopes)
        credentials = flow.run_console()
        with open("CREDENTIALS_PICKLE_FILE", 'wb') as f:
            pickle.dump(credentials, f)
    return googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)
if __name__ == "__main__":
    main()

Chargui Taieb
  • 75
  • 1
  • 10

1 Answers1

0

I luckily found the solution to this problem, and here a sample working script that will list all the video you have in ur YouTube channel and will ask for authorization Code just one time.

i know it's a bit messy but it's ok

import os
import sys
file_path = os.path.dirname(__file__)
module_path = os.path.join(file_path, "lib")
sys.path.append(module_path)
import httplib2
import json
import argparse
import re
import random
from pytz import timezone
from dateutil import parser
from datetime import datetime
from googleapiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow

random.seed()
CLIENT_SECRETS_FILE = "credentials.json"
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0
To make this sample run you will need to populate the client_secrets.json file
found at:   %swith information from the Developers Console
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),CLIENT_SECRETS_FILE))

scopes = [
    "https://www.googleapis.com/auth/youtube",
    "https://www.googleapis.com/auth/youtube.upload",
    "https://www.googleapis.com/auth/youtubepartner",
    "https://www.googleapis.com/auth/youtube.force-ssl",
    ]
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,message=MISSING_CLIENT_SECRETS_MESSAGE, scope=scopes)

storage = Storage("%s-oauth2.json" % sys.argv[0])
credentials = storage.get()
if credentials is None or credentials.invalid:
  flags = argparser.parse_args()
  credentials = run_flow(flow, storage, flags)

youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
  http=credentials.authorize(httplib2.Http()))

channels_response = youtube.channels().list(
  mine=True,
  part="contentDetails"
).execute()

for channel in channels_response["items"]:
  uploads_list_id = channel["contentDetails"]["relatedPlaylists"]["uploads"]
  print("Videos in list {0:s}".format(uploads_list_id),file=sys.stderr)
  playlistitems_list_request = youtube.playlistItems().list(
    playlistId=uploads_list_id,
    part="snippet",
    maxResults=50
  )

playlistitems_list_response = playlistitems_list_request.execute()


for playlist_item in playlistitems_list_response["items"]:
    title = playlist_item["snippet"]["title"]
    video_id = playlist_item["snippet"]["resourceId"]["videoId"]
    video_list_request = youtube.videos().list(
    id=video_id,
    part="snippet,fileDetails,statistics,status",
    maxResults=50
    )
    video_list_response = video_list_request.execute()
    for video_list_item in video_list_response["items"]:
        print(title)
        print (video_id)
        print (video_list_item["fileDetails"]["fileName"])
        print (video_list_item["statistics"]["viewCount"])
        print (video_list_item["statistics"]["likeCount"])
        print (video_list_item["snippet"]["description"])
        print (video_list_item["snippet"]["publishedAt"])
        print (video_list_item["status"]["privacyStatus"])
       


Chargui Taieb
  • 75
  • 1
  • 10