Интеграция API Spotify и Youtube: понравившиеся Youtube musi c видео в Spotify - PullRequest
0 голосов
/ 29 апреля 2020

Обзор проекта.

Используемый API

  • Использование API Spotify для создания списка воспроизведения и добавления musi c в список воспроизведения
  • Использование Youtube API данных для получения понравившихся видео
  • OAuth 2.0 для проверки

Цель:

  • Любимые видеоролики YouTube из моей учетной записи YouTube должны автоматически появиться в моем Spotify Недавно созданный список воспроизведения

Код:

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()

Выход

  • Новый список воспроизведения создается внутри spotify libray, но песня в списке отсутствует принадлежат мои любимые видео и песни повторяются в плейлисте, количество песен почти 5-6, и все они одинаковы

Ссылка песни: https://www.youtube.com/watch?v=4awXLGzlf7E

Заранее спасибо за помощь.

...