56 lines
1.8 KiB
Python
56 lines
1.8 KiB
Python
#!/usr/bin/env python3
|
|
|
|
# Python wrapper for REST API for some of the YouTube API.
|
|
from requests import get, post
|
|
import json
|
|
|
|
class YouTubeAPI(object):
|
|
def __init__(self, key):
|
|
self.url = 'https://www.googleapis.com/youtube/v3/'
|
|
self.key = key
|
|
|
|
# Sends get requests and turns requested data.
|
|
def getRequest(self, domain):
|
|
response = get('{}{}&key={}'.format(self.url,
|
|
domain,
|
|
self.key))
|
|
return json.loads(response.text)
|
|
|
|
def getVideo(self, part, id):
|
|
return self.getRequest('videos?part={}&id={}'.format(part, id))
|
|
|
|
def getVideoInfo(self, id):
|
|
snippet = self.getVideo('snippet', id)
|
|
status = self.getVideo('status', id)
|
|
|
|
# Check for private videos
|
|
if len(snippet['items']) == 0:
|
|
return '', '', '', '', '', '', 'private', id
|
|
snippet = snippet['items'][0]['snippet']
|
|
status = status['items'][0]['status']
|
|
title = snippet['title']
|
|
date = snippet['publishedAt']
|
|
channel = snippet['channelTitle']
|
|
channelId = snippet['channelId']
|
|
description = snippet['description']
|
|
try:
|
|
tags = snippet['tags']
|
|
except:
|
|
tags = ''
|
|
privacy = status['privacyStatus']
|
|
return title, date, channel, channelId, description, tags, privacy, id
|
|
|
|
def getPlaylist(self, id, pageToken=''):
|
|
if(pageToken):
|
|
pageToken = '&pageToken={}'.format(pageToken)
|
|
return self.getRequest('playlistItems?part=snippet&maxResults=50&playlistId={}{}'.format(id,
|
|
pageToken))
|
|
|
|
def getPlaylistVideos(self, id):
|
|
playlist = self.getPlaylist(id)
|
|
items = playlist['items']
|
|
while 'nextPageToken' in playlist:
|
|
playlist = self.getPlaylist(id, playlist['nextPageToken'])
|
|
items.extend(playlist['items'])
|
|
return items
|