playlists.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from lib import debug
  2. def add_to_playlist(youtube, video_id, options):
  3. # find playlist with given name
  4. existing_playlist_id = None
  5. playlists = youtube.playlists()
  6. request = playlists.list(mine=True, part='id,snippet')
  7. while request is not None:
  8. results = request.execute()
  9. for item in results['items']:
  10. if item.get('snippet', {}).get('title') == options.playlist:
  11. existing_playlist_id = item.get('id')
  12. # stop paginating playlists on first matching playlist title
  13. if existing_playlist_id is None:
  14. request = playlists.list_next(request, results)
  15. else:
  16. break
  17. # create playlist, if necessary
  18. if existing_playlist_id is None:
  19. playlists_insert_response = youtube.playlists().insert(part="snippet,status", body={
  20. "snippet": {
  21. "title": options.playlist
  22. },
  23. "status": {
  24. "privacyStatus": options.privacy
  25. }
  26. }).execute()
  27. existing_playlist_id = playlists_insert_response.get('id', None)
  28. # something has gone wrong
  29. if existing_playlist_id is None:
  30. debug('Error creating playlist')
  31. else:
  32. # add video to playlist
  33. youtube.playlistItems().insert(part='snippet', body={
  34. "snippet": {
  35. "playlistId": existing_playlist_id,
  36. "resourceId": {
  37. "kind": "youtube#video",
  38. "videoId": video_id
  39. }
  40. }
  41. }).execute()
  42. debug("Added video to playlist '{0}'".format(options.playlist))