Создайте новый список воспроизведения spotify - скрипт не работает - PullRequest
0 голосов
/ 28 февраля 2020

Я новичок в python и хочу сделать свой первый проект, вставив URL-адрес видео с музыкой Youtube c и создав плейлист в Spotify, содержащий песню в URL.

Для некоторых причина, мой сценарий не работает. Я хотел бы знать, почему . Как только я запустил скрипт, я получил это обратно:

Initialising Spotify Client....

                User authentication requires interaction with your
                web browser. Once you enter your credentials and
                give authorization, you will be redirected to
                a url.  Paste that url you were directed to to
                complete the authorization.

и затем скопировал URL в консоль (страница не работает, потому что она "'http://localhost: 8888 / callback / '") и все; Мой сценарий больше не запускается.

ЭТО МОЙ СЦЕНАРИЙ ->

import json
import requests
from youtube_dl import YoutubeDL
import spotipy.util as util
import spotipy

username = '***' #personal
client_id = '***'  #personal
client_secret = '***'  #personal
redirect_uri = 'http://localhost:8888/callback/'
scope = 'playlist-modify-private'


def init_spotify_client():
        print('Initialising Spotify Client....')
        token = util.prompt_for_user_token(username, scope,
                                           client_id=client_id,
                                           client_secret=client_secret,
                                           redirect_uri=redirect_uri)
        client_token = spotipy.Spotify(auth=token)
        print('\nClient initialised!\n')
        return client_token

class CreatePlaylist:
        def __init__(self,youtube_url):
            self.youtube_url = youtube_url

        def info(self,youtube_url):
            # use youtube_dl to collect the song name & artist name
            video = YoutubeDL().extract_info(youtube_url, download=False)
            song_name = video["track"]
            artist = video["artist"]

        def create_playlist(self):
            """Create A New Playlist"""
            request_body = json.dumps({
                "name": "Youtube Liked Vids",
                "description": "All Liked Youtube Videos",
                "public": False
            })

            query = "https://api.spotify.com/v1/users/{}/playlists".format(username)
            response = requests.post(
                query,
                data=request_body,
                headers={
                    "Content-Type": "application/json",
                    "Authorization": "Bearer {}".format(init_spotify_client())
                }
            )
            response_json = response.json()

            # playlist id
            return response_json["id"]

        def add_song_to_playlist(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(init_spotify_client())
                }
            )
            response_json = response.json()
            songs = response_json["tracks"]["items"]

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

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

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

            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(init_spotify_client())
                }
            )
            response_json = response.json()
            return response_json

def main():
        init_spotify_client()
        url = "https://www.youtube.com/watch?v=Bx5QlA8xp28"
        cp = CreatePlaylist(url)
main()

Скажите, пожалуйста, что не так: /

1 Ответ

0 голосов
/ 28 февраля 2020

Вы не вызвали метод add_song_to_playlist. Насколько я понимаю, вы передаете переменные song_name и artist из метода info для вызова add_song_to_playlist. Если это так, вам нужно добавить оператор возврата в метод info следующим образом:

def info(self,youtube_url):
    # use youtube_dl to collect the song name & artist name
    video = YoutubeDL().extract_info(youtube_url, download=False)
    song_name = video["track"]
    artist = video["artist"]
    return song_name, artist

В вашей функции main вам нужно вызвать метод info и использовать результат что называть add_song_to_playlist:

def main():
    init_spotify_client()
    url = "https://www.youtube.com/watch?v=Bx5QlA8xp28"
    cp = CreatePlaylist(url)
    song_name, artist = cp.info()
    res = cp.add_song_to_playlist(song_name, artist)
...