parent
14b2a923f7
commit
ebdc67b85b
@ -1,3 +1,4 @@
|
||||
google-api-python-client
|
||||
irc
|
||||
python-dateutil
|
||||
requests
|
||||
|
@ -0,0 +1,50 @@
|
||||
import googleapiclient
|
||||
import googleapiclient.discovery
|
||||
|
||||
|
||||
BASE_URL = 'https://www.youtube.com'
|
||||
|
||||
|
||||
class Youtube(object):
|
||||
def __init__(self, api_key, log=None):
|
||||
self.client = googleapiclient.discovery.build('youtube', 'v3', developerKey=api_key)
|
||||
self.log = log
|
||||
|
||||
def _search(self, channel_id, query, playlists, limit):
|
||||
result = []
|
||||
count = limit
|
||||
token = ''
|
||||
while True:
|
||||
resp = self.client.search().list(
|
||||
channelId=channel_id,
|
||||
q=query,
|
||||
safeSearch='none',
|
||||
type='playlist' if playlists else 'video',
|
||||
maxResults=min(count, 50),
|
||||
part='id,snippet',
|
||||
pageToken=token).execute()
|
||||
for item in resp.get('items', []):
|
||||
kind = item['id']['kind'].split('youtube#')[1]
|
||||
if kind == 'playlist':
|
||||
url = '{0}/view_play_list?p={1}'.format(BASE_URL, item['id']['playlistId'])
|
||||
else:
|
||||
url = '{0}/watch?v={1}'.format(BASE_URL, item['id']['videoId'])
|
||||
result.append(dict(
|
||||
kind=kind,
|
||||
url=url,
|
||||
title=item['snippet']['title']))
|
||||
count -= resp['pageInfo']['resultsPerPage']
|
||||
if count <= 0:
|
||||
break
|
||||
token = resp.get('nextPageToken')
|
||||
if not token:
|
||||
break
|
||||
return result
|
||||
|
||||
def search(self, channel_id, query, playlists=True, limit=None):
|
||||
try:
|
||||
return self._search(channel_id, query, playlists, limit)
|
||||
except googleapiclient.errors.HttpError as e:
|
||||
if self.log:
|
||||
self.log.error('Failed to query Youtube API: %s', str(e))
|
||||
return None
|
Loading…
Reference in new issue