diff options
Diffstat (limited to 'youtube/youtube.py')
| -rw-r--r-- | youtube/youtube.py | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/youtube/youtube.py b/youtube/youtube.py new file mode 100644 index 0000000..bcbff21 --- /dev/null +++ b/youtube/youtube.py | |||
| @@ -0,0 +1,44 @@ | |||
| 1 | #!/usr/bin/env python3 | ||
| 2 | |||
| 3 | from urllib import parse, request | ||
| 4 | import json | ||
| 5 | |||
| 6 | |||
| 7 | class Youtube: | ||
| 8 | |||
| 9 | def __init__(self, api_key): | ||
| 10 | self.api_key = api_key | ||
| 11 | |||
| 12 | def _api_call(self, section, parameters): | ||
| 13 | parameters["key"] = self.api_key | ||
| 14 | data = parse.urlencode(parameters) | ||
| 15 | api_base = "https://www.googleapis.com/youtube/v3" | ||
| 16 | response = request.urlopen("%s/%s?%s" % (api_base, section, data)) | ||
| 17 | return json.loads(response.read().decode("UTF-8"))["items"] | ||
| 18 | |||
| 19 | def search(self, query): | ||
| 20 | return self._api_call("search", {"part": "snippet", | ||
| 21 | "q": query}) | ||
| 22 | |||
| 23 | def get_channel(self, username): | ||
| 24 | return self._api_call("channels", {"part": "snippet", | ||
| 25 | "forUsername": username}) | ||
| 26 | |||
| 27 | def get_uploads(self, channel): | ||
| 28 | content_details = self._api_call("channels", {"part": "contentDetails", | ||
| 29 | "id": channel["id"]}) | ||
| 30 | uploads_id = content_details[0]["contentDetails"]["relatedPlaylists"]["uploads"] | ||
| 31 | return self._api_call("playlists", {"part": "snippet", | ||
| 32 | "id": uploads_id}) | ||
| 33 | |||
| 34 | def get_playlists(self, channel, max_results=5): | ||
| 35 | return self._api_call("playlists", {"part": "snippet", | ||
| 36 | "channelId": channel["id"], | ||
| 37 | "maxResults": max_results}) | ||
| 38 | |||
| 39 | def get_playlist_items(self, playlist, max_results=5): | ||
| 40 | return self._api_call("playlistItems", {"part": "snippet", | ||
| 41 | "playlistId": playlist["id"], | ||
| 42 | "maxResults": max_results}) | ||
| 43 | |||
| 44 | # vim: set ts=8 sw=4 tw=0 et : | ||
