· 5 years ago · Dec 26, 2020, 04:06 PM
1from googleapiclient.discovery import build
2import googleapiclient.discovery
3import os, sys, json
4
5
6#read any json file
7def ReadJSON(path):
8 with open(path, 'r') as file:
9 return json.load(file)
10
11#Send the request for googleapiclient.discovery.build
12def GoogleClientRequest(apiKey):
13 try:
14 youtube = googleapiclient.discovery.build('youtube', 'v3', developerKey = apiKey)
15 except Exception:
16 sys.exit("Unvalid API key.\nTry again!")
17
18 return youtube
19
20#get the api key
21def GetAPIkey():
22 return ReadJSON("configurations.json")["Google API Key"]
23
24#get all the videos of that playlist
25def PlaylistItems(pl_id, youtube):
26 videoIds = []
27 pl_request = youtube.playlistItems().list(
28 part="snippet",
29 playlistId=pl_id
30 )
31 pl_response = pl_request.execute()
32
33 for item in pl_response["items"]:
34 videoIds.append(item.get("snippet").get("title"))
35 return videoIds
36
37#input
38def InputFile():
39 print("______________________________\nWrite the playlist link: ", end="")
40 pl_link = input()
41 if(pl_link == "x"):
42 sys.exit("______________________________")
43 print("______________________________\n")
44
45 if(pl_link[0] == "="):
46 return pl_link[1:]
47 else:
48 print(pl_link[len("https://www.youtube.com/playlist?list="):])
49 return pl_link[len("https://www.youtube.com/playlist?list="):]
50
51def Output(pl_id, videolist):
52 # this where you change the directory of the output files!!!!!!!!!!!!!!!!!!!!!!!!!
53 # filename = directory + pl_id + ".txt"
54 filename = pl_id + ".txt"
55 with open(filename, "w+") as pl_file:
56 for video in videolist:
57 pl_file.write(video + "\n")
58
59
60#main
61GoogleAPI = GetAPIkey()
62youtube = GoogleClientRequest(GoogleAPI)
63while(True):
64 pl_id = InputFile()
65 videoIds = PlaylistItems(pl_id, youtube)
66 Output(pl_id, videoIds)