From 2959673f74c9a6ca6ad5a3426d68cb7890fc48c4 Mon Sep 17 00:00:00 2001 From: Ethan Dalool Date: Sun, 21 May 2017 13:50:17 -0700 Subject: [PATCH] Add Youtube.get_related_videos --- ytapi.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/ytapi.py b/ytapi.py index 3071148..b205f5b 100644 --- a/ytapi.py +++ b/ytapi.py @@ -26,6 +26,9 @@ class Video: best_thumbnail = max(thumbnails, key=lambda x: thumbnails[x]['width'] * thumbnails[x]['height']) self.thumbnail = thumbnails[best_thumbnail] + def __str__(self): + return 'Video:%s' % self.id + class Youtube: def __init__(self, key): @@ -68,6 +71,23 @@ class Youtube: if page_token is None or count < 50: break + def get_related_videos(self, video_id, part='id,snippet', count=50): + if isinstance(video_id, Video): + video_id = video_id.id + + results = self.youtube.search().list( + part=part, + relatedToVideoId=video_id, + type='video', + maxResults=count, + ).execute() + videos = [] + for related in results['items']: + related['id'] = related['id']['videoId'] + video = Video(related) + videos.append(video) + return videos + def get_video(self, video_ids): if isinstance(video_ids, str): singular = True @@ -81,7 +101,7 @@ class Youtube: chunk = ','.join(chunk) data = self.youtube.videos().list(part='snippet', id=chunk).execute() items = data['items'] - results += items + results.extend(items) results = [Video(snippet) for snippet in results] if singular: if len(results) == 1: