Поддерживается только действительная аутентификация на носителе - Python - Spotify API - PullRequest
0 голосов
/ 22 марта 2020

Я кодировал этот скрипт, который может входить в мои любимые видео и создавать плейлист на Spotify с названием и исполнителем каждого видео.

Я уже пытался обновить токен от менеджера API Spotify, но по какой-то причине по-прежнему отображается следующая ошибка:

  status': 400, 'message': 'Only valid bearer authentication supported'}}
Traceback (most recent call last):
  File "/Users/gzangerme/Desktop/Python Project/SpotifyAutomation.py", line 159, in <module>
    cp.add_song_to_playlist()
  File "/Users/gzangerme/Desktop/Python Project/SpotifyAutomation.py", line 129, in add_song_to_playlist
    self.get_liked_videos()
  File "/Users/gzangerme/Desktop/Python Project/SpotifyAutomation.py", line 76, in get_liked_videos
    "spotify_uri": self.get_spotify_uri(song_name, artist)
  File "/Users/gzangerme/Desktop/Python Project/SpotifyAutomation.py", line 119, in get_spotify_uri
    songs = response_json["tracks"]["items"]
KeyError: 'tracks'

Я заметил, что KeyError отображается, потому что вызов возвращает ошибку.

Ниже приведен код для проекта:

import json
import requests
import os
from secrets import spotify_user_id, spotify_token
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
import youtube_dl



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 = {}

    #Step 1
    def get_youtube_client(self):
        os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

        api_service_name = "youtube"
        api_version = "v3"

        #Get Credentials for API Client
        flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file('client_secret.json', scopes=['https://www.googleapis.com/auth/youtube'])
        credentials = flow.run_console()
        youtube_client = googleapiclient.discovery.build(api_service_name, api_version, credentials=credentials)

        return youtube_client

    #Step 2
    def get_liked_video(self):
        request = self.youtube_client.videos().list(
            part="snippet,contentDetails,statistics",
            myRating="Like"
        )
        response = request.execute()

        #Get information on each video on the list
        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 colect the name of the song and the artist

            video = youtube_dl.YoutubeDL({}).extract_info(youtube_url,download = False)
            song_name = video["track"]
            artist = video["artist"]

            self.all_song_info[video_title] = {
                "youtube_url":youtube_url,
                "song_name":song_name,
                "artist":artist,
                "spotify_uri":self.get_spotify_uri(song_name,artist)
            }

    #Step 3
    def create_playlist(self):
        request_body = json.dumps({
            "name":"Youtube Liked Videos",
            "description":"Todos os Videos com Like do YT",
            "public": True
        })
        query = "https://api.spotify.com/v1/users/{user_id}/playlists".format()
        response = requests.post(
            query,
            data= request_body,
            headers={
                "Content-type": "application/json",
                "Authorization": "Bearer {}".format(spotify_token)
            }
        )
        response_json = response.json

        #playlistId
        return response_json["id"]

    #Step 4
    def get_spotify_uri(self, song_name, artist):
        query = "https://api.spotify.com/v1/search".format(
        song_name, 
        artist
        )
        response = requests.get(
            query,
            headers={
                "Content-type": "application/json",
                "Authorization": "Bearer {}".format(spotify_token)
            }
        )
        response_json = response.json()
        songs = response_json["tracks"]["items"]

        #configurar para utilizar somente a primeira musica
        uri = songs[0]["uri"]
        return uri

    #Step 5
    def add_song_to_playlist(self):

        self.get_liked_video()

        uris = []
        for song ,info in self.all_song_info():
            uris.apend(info["spotify_uri"])

        #create new playlist
        playlist_id = self.create_playlist

        #add musics to the created playlist
        request_data = json.dumps(uris)

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

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

        response_json = response.json()
        return response_json


CreatePlaylist()

1 Ответ

1 голос
/ 22 марта 2020

Я думаю, что spotify_token и spotify_user_id являются проблемой. Если вы go to: https://pypi.org/project/spotify-token/, это скрипт Python, в котором вы можете сгенерировать токен Spotify.

Что касается spotify_user_id, который является вашим именем пользователя в Spotify. Чтобы найти свое имя пользователя, go to: https://www.spotify.com/us/, нажмите Профиль> Аккаунт> Обзор аккаунта

Надеюсь, это поможет.

...