-
Notifications
You must be signed in to change notification settings - Fork 63
/
youtube_api_cmd.py
304 lines (240 loc) · 9.59 KB
/
youtube_api_cmd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
"""
-*- coding: utf-8 -*-
========================
Python YouTube API
========================
Developed by: Chirag Rathod (Srce Cde)
Email: [email protected]
========================
"""
import json
import sys
from urllib import *
import argparse
from urllib.parse import urlparse, urlencode, parse_qs
from urllib.request import urlopen
YOUTUBE_COMMENT_URL = "https://www.googleapis.com/youtube/v3/commentThreads"
YOUTUBE_SEARCH_URL = "https://www.googleapis.com/youtube/v3/search"
class YouTubeApi:
def load_comments(self, mat):
for item in mat["items"]:
comment = item["snippet"]["topLevelComment"]
author = comment["snippet"]["authorDisplayName"]
text = comment["snippet"]["textDisplay"]
print("Comment by {}: {}".format(author, text))
if "replies" in item.keys():
for reply in item["replies"]["comments"]:
rauthor = reply["snippet"]["authorDisplayName"]
rtext = reply["snippet"]["textDisplay"]
print("\n\tReply by {}: {}".format(rauthor, rtext), "\n")
def get_video_comment(self):
parser = argparse.ArgumentParser()
mxRes = 20
vid = str()
parser.add_argument(
"--c",
help="calls comment function by keyword function",
action="store_true",
)
parser.add_argument("--max", help="number of comments to return")
parser.add_argument(
"--videourl", help="Required URL for which comments to return"
)
parser.add_argument("--key", help="Required API key")
args = parser.parse_args()
if not args.max:
args.max = mxRes
if not args.videourl:
exit("Please specify video URL using the --videourl=parameter.")
if not args.key:
exit("Please specify API key using the --key=parameter.")
try:
video_id = urlparse(str(args.videourl))
q = parse_qs(video_id.query)
vid = q["v"][0]
except:
print("Invalid YouTube URL")
parms = {
"part": "snippet,replies",
"maxResults": args.max,
"videoId": vid,
"textFormat": "plainText",
"key": args.key,
}
try:
matches = self.openURL(YOUTUBE_COMMENT_URL, parms)
i = 2
mat = json.loads(matches)
nextPageToken = mat.get("nextPageToken")
print("\nPage : 1")
print("------------------------------------------------------------------")
self.load_comments(mat)
while nextPageToken:
parms.update({"pageToken": nextPageToken})
matches = self.openURL(YOUTUBE_COMMENT_URL, parms)
mat = json.loads(matches)
nextPageToken = mat.get("nextPageToken")
print("\nPage : ", i)
print(
"------------------------------------------------------------------"
)
self.load_comments(mat)
i += 1
except KeyboardInterrupt:
print("User Aborted the Operation")
except:
print("Cannot Open URL or Fetch comments at a moment")
def load_search_res(self, search_response):
videos, channels, playlists = [], [], []
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
videos.append(
"{} ({})".format(
search_result["snippet"]["title"],
search_result["id"]["videoId"],
)
)
elif search_result["id"]["kind"] == "youtube#channel":
channels.append(
"{} ({})".format(
search_result["snippet"]["title"],
search_result["id"]["channelId"],
)
)
elif search_result["id"]["kind"] == "youtube#playlist":
playlists.append(
"{} ({})".format(
search_result["snippet"]["title"],
search_result["id"]["playlistId"],
)
)
print("Videos:\n", "\n".join(videos), "\n")
print("Channels:\n", "\n".join(channels), "\n")
print("Playlists:\n", "\n".join(playlists), "\n")
def search_keyword(self):
parser = argparse.ArgumentParser()
mxRes = 20
parser.add_argument(
"--s", help="calls the search by keyword function", action="store_true"
)
parser.add_argument(
"--r",
help="define country code for search results for specific country",
default="IN",
)
parser.add_argument("--search", help="Search Term", default="Srce Cde")
parser.add_argument("--max", help="number of results to return")
parser.add_argument("--key", help="Required API key")
args = parser.parse_args()
if not args.max:
args.max = mxRes
if not args.key:
exit("Please specify API key using the --key= parameter.")
parms = {
"q": args.search,
"part": "id,snippet",
"maxResults": args.max,
"regionCode": args.r,
"key": args.key,
}
try:
matches = self.openURL(YOUTUBE_SEARCH_URL, parms)
search_response = json.loads(matches)
i = 2
nextPageToken = search_response.get("nextPageToken")
print("\nPage : 1 --- Region : {}".format(args.r))
print("------------------------------------------------------------------")
self.load_search_res(search_response)
while nextPageToken:
parms.update({"pageToken": nextPageToken})
matches = self.openURL(YOUTUBE_SEARCH_URL, parms)
search_response = json.loads(matches)
nextPageToken = search_response.get("nextPageToken")
print("Page : {} --- Region : {}".format(i, args.r))
print(
"------------------------------------------------------------------"
)
self.load_search_res(search_response)
i += 1
except KeyboardInterrupt:
print("User Aborted the Operation")
except:
print("Cannot Open URL or Fetch comments at a moment")
def load_channel_vid(self, search_response):
videos = []
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
videos.append(
"{} ({})".format(
search_result["snippet"]["title"],
search_result["id"]["videoId"],
)
)
print("###Videos:###\n", "\n".join(videos), "\n")
def channel_videos(self):
parser = argparse.ArgumentParser()
mxRes = 20
parser.add_argument(
"--sc",
help="calls the search by channel by keyword function",
action="store_true",
)
parser.add_argument("--channelid", help="Search Term", default="Srce Cde")
parser.add_argument("--max", help="number of results to return")
parser.add_argument("--key", help="Required API key")
args = parser.parse_args()
if not args.max:
args.max = mxRes
if not args.channelid:
exit("Please specify channelid using the --channelid= parameter.")
if not args.key:
exit("Please specify API key using the --key= parameter.")
parms = {
"part": "id,snippet",
"channelId": args.channelid,
"maxResults": args.max,
"key": args.key,
}
try:
matches = self.openURL(YOUTUBE_SEARCH_URL, parms)
search_response = json.loads(matches)
i = 2
nextPageToken = search_response.get("nextPageToken")
print("\nPage : 1")
print("------------------------------------------------------------------")
self.load_channel_vid(search_response)
while nextPageToken:
self.parms.update({"pageToken": nextPageToken})
matches = self.openURL(YOUTUBE_SEARCH_URL, parms)
search_response = json.loads(matches)
nextPageToken = search_response.get("nextPageToken")
print("Page : ", i)
print(
"------------------------------------------------------------------"
)
self.load_channel_vid(search_response)
i += 1
except KeyboardInterrupt:
print("User Aborted the Operation")
except:
print("Cannot Open URL or Fetch comments at a moment")
def openURL(self, url, parms):
f = urlopen(url + "?" + urlencode(parms))
data = f.read()
f.close()
matches = data.decode("utf-8")
return matches
def main():
y = YouTubeApi()
if str(sys.argv[1]) == "--s":
y.search_keyword()
elif str(sys.argv[1]) == "--c":
y.get_video_comment()
elif str(sys.argv[1]) == "--sc":
y.channel_videos()
else:
print(
"Invalid Arguments\nAdd --s for searching video by keyword after the filename\nAdd --c to list comments after the filename\nAdd --sc to list vidoes based on channel id"
)
if __name__ == "__main__":
main()