-
Notifications
You must be signed in to change notification settings - Fork 2
/
YoutubeAPI.py
77 lines (57 loc) · 2.04 KB
/
YoutubeAPI.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
import requests
from os import environ
class YoutubeAPI(object):
def __init__(self):
try:
self.key = environ["YOUTUBE_KEY"]
except:
keys = open(".keys")
keys.readline()
keys.readline()
self.key = keys.readline()[:-1]
keys.close()
def search_video(self, query):
args = {"key": self.key,
"type": "video",
"q": query,
"part": "snippet"}
r = requests.get(
"https://www.googleapis.com/youtube/v3/search",
params=args)
data = r.json()["items"]
to_return = "https://www.youtube.com/watch?v=" + data[0]["id"]["videoId"]
return to_return
def get_channel_id(self, user):
args = {"key": self.key,
"part": "snippet",
"q": user,
"type": "channel"}
r = requests.get(
"https://www.googleapis.com/youtube/v3/search",
params=args)
channel_id = r.json()["items"][0]["id"]["channelId"]
return channel_id
def latest_vids(self, query, number=3):
args = {
"key": self.key,
"part": "snippet",
"channelId": self.get_channel_id(query),
"order": "date"}
r = requests.get(
"https://www.googleapis.com/youtube/v3/search",
params=args)
data = r.json()["items"]
to_return = ""
for video in range(number):
to_return = to_return + "https://www.youtube.com/watch?v=" + data[video]["id"]["videoId"] + "\n"
return to_return
def get_thumbnail(self, query):
args = {"key": self.key,
"type": "video",
"q": query,
"part": "snippet"}
r = requests.get(
"https://www.googleapis.com/youtube/v3/search",
params=args)
thumbnail_url = r.json()["items"][0]["snippet"]["thumbnails"]["high"]["url"]
return thumbnail_url