Spotify & Youtube API integration: Liked Youtube music videos in Spotify

本小妞迷上赌 提交于 2020-06-29 05:08:12

问题


An overview of the project.

API Used

  • Using Spotify API to Create a Playlist and add music to the playlist
  • Using Youtube Data API to retrieve liked videos
  • OAuth 2.0 for verification

Goal:

  • The liked youtube videos of my youtube account should automatically come inside my Spotify newly created playlist

Code:

import json
import os

import google_auth_oauthlib.flow
import google.oauth2.credentials
import googleapiclient.discovery
import googleapiclient.errors
import requests
import youtube_dl

from secret import spotify_token, spotify_user_id
from exceptions import ResponseException


class CreatePlaylist:

    def __init__(self):
        self.user_id = spotify_user_id
        self.spotify_token = spotify_token
        self.youtube_client = self.get_youtube_client()
        self.all_song_info = {}
# connect to youtube data api

    def get_youtube_client(self):

        # Disable OAuthlib's HTTPS verification when running locally.
        # *DO NOT* leave this option enabled in production.
        os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

        api_service_name = "youtube"
        api_version = "v3"
        client_secrets_file = "youtube_auth.json"

        # Get credentials and create an API client
        scopes = ["https://www.googleapis.com/auth/youtube.readonly"]
        flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
            client_secrets_file, scopes)
        credentials = flow.run_console()

        # from the Youtube DATA API
        youtube_client = googleapiclient.discovery.build(
            api_service_name, api_version, credentials=credentials)

        return youtube_client

    # remove **kwarg that are not set

    def get_liked_videos(self):

        request = self.youtube_client.videos().list(
            part="snippet,contentDetails,statistics", myRating="like"
        )

        response = request.execute()

        # collect each video and get important information
        for item in response['items']:
            video_title = item['snippet']['title']
            youtube_url = "https://www.youtube.com/watch?v={}".format(
                item["id"])

        # use youtube_dl to collect song name and artist name
            video = youtube_dl.YoutubeDL({}).extract_info(
                youtube_url, download=False)

            song_name = video['track']
            artist = video['artist']

            # save all important info and skip any missing song and artist
            self.all_song_info[video_title] = {
                "youtube_url": youtube_url,
                "song_name": song_name,
                "artist": artist,
                # add the uri, easy to get song to put into playlist
                "spotify_uri": self.get_spotify_uri(song_name, artist)
            }

# create a new playlist

    def create_playlist(self):

        request_body = json.dumps({
            "name": "Youtube Liked Songs",
            "description": "All liked youtube video songs",
            "public": True
        })
        query = "https://api.spotify.com/v1/users/{}/playlists".format(
            self.user_id)
        response = requests.post(
            query,
            data=request_body,
            headers={
                "Content-Type": "application/json",
                "Authorization": "Bearer {}".format(self.spotify_token)
            }
        )
        response_json = response.json()
        # playlis id
        return response_json["id"]

# search for the song on Spotify

    def get_spotify_uri(self, song_name, artist):

        query = "https://api.spotify.com/v1/search?query=track%3A{}+artist%3A{}&type=track&offset=0&limit=20".format(
            song_name,
            artist
        )
        response = requests.get(
            query,
            headers={
                "Content-Type": "application/json",
                "Authorization": "Bearer {}".format(self.spotify_token)
            }
        )
        response_json = response.json()
        songs = response_json["tracks"]["items"]

        # only use the first song
        uri = songs[0]["uri"]
        return uri

# add the song in new spotify_playlist
    def add_song_to_playlist(self):

        # populate dictionary with our liked songs
        self.get_liked_videos()

        # collect all of uri
        uris = []
        for song, info in self.all_song_info.items():
            uris.append(info['spotify_uri'])

        # create a new playlist
        playlist_id = self.create_playlist()

        # add all songs into new playlist
        request_data = json.dumps(uris)

        query = "https://api.spotify.com/v1/playlists/{}/tracks".format(
            playlist_id)

        response = requests.post(
            query,
            data=request_data,
            headers={
                "Content-Type": "application/json",
                "Authorization": "Bearer {}".format(self.spotify_token)
            })

        if response.status_code < 200 or response.status_code > 300:
            raise ResponseException(response.status_code)

        response_json = response.json()
        return response_json


if __name__ == '__main__':
    cp = CreatePlaylist()
    cp.add_song_to_playlist()

Output

  • A new playlist is made inside spotify libray but the song in the list doesn't belong to my liked videos and the songs are repeated in the playlist the number of songs are almost 5-6 and all are same

Link of the song: https://www.youtube.com/watch?v=4awXLGzlf7E

Thanks in advance kinda help.

来源:https://stackoverflow.com/questions/61509715/spotify-youtube-api-integration-liked-youtube-music-videos-in-spotify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!