currently_playing 使用 Spotipy 库时不工作

currently_playing not working when using the Spotipy library

我正在尝试访问用户当前正在使用 spotipy Spotify python 库播放的音乐。

import json
import spotipy
import spotipy.util as util
from spotipy.oauth2 import SpotifyClientCredentials 

cid = "xxx"
csecret = "xxx"
redirectURI = "xxx"
username = "xxx"

client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=csecret) 
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

scope = 'user-read-currently-playing'
token = util.prompt_for_user_token(username, scope, cid, csecret, redirectURI)

if token:
    sp = spotipy.Spotify(auth=token)
else:
    print("Can't get token for", username)

current_track = sp.current_user_playing_track()
print(json.dumps(current_track, sort_keys=False, indent=4))

我也试过使用 sp.currently_playing()。我能够访问其他数据,例如 sp.current_user_saved_tracks(limit=3, offset=0)。使用我目前拥有的,它总是错误地说 AttributeError: 'Spotify' object has no attribute 'current_user_playing_track'。我已经探索过使用节点,但我真的很想坚持使用 python.

您正在尝试使用最新发布版本中没有的功能。

可以看到on PyPI that the current version was released on 5 Jan 2017, but you can see on Github你要调用的函数是2017年5月13日添加的

Issue #270 and Issue #211 都在询问何时将新版本推送到 PyPI,(此外,版本编号存在一些奇怪的问题。)

无论如何,正如#211所说:

If you're running into issues still, you can install the package directly from the github repo.

pip install git+https://github.com/plamere/spotipy.git --upgrade

所以我也一直在尝试访问我当前的歌曲,在 3 天后跟踪网络上的每个错误答案... 我正在使用 Authorization Code Flow,如此处所述 https://spotipy.readthedocs.io/en/2.12.0/#client-credentials-flow

Only endpoints that do not access user information can be accessed

由于无法设置环境变量,我用另一个脚本来设置。

请注意,您应该添加重定向 link 例如“https://localhost:8000/" in https://developer.spotify.com/dashboard/applications/.


这是我用来添加信用的代码:

import os

class SetCreditentials:

    def __init__(self):
        self.CLIENT_SECRET = os.getenv('SPOTIPY_CLIENT_SECRET')
        self.CLIENT_ID = os.getenv('SPOTIPY_CLIENT_ID')
        self.REDIRECT_URI = os.getenv('SPOTIPY_REDIRECT_URI')
        os.environ['SPOTIPY_CLIENT_ID'] = ""
        os.environ['SPOTIPY_CLIENT_SECRET'] = ""
        os.environ['SPOTIPY_REDIRECT_URI'] = "http://localhost:8000/"

这里是访问任何数据的代码(这里是当前播放曲目):

import spotipy.util as util
import spotipy
import Creditentials

# Authorization Code Flow
user = "213tzif5o7rzyxtijuqdgtfuq"
scope = "user-read-currently-playing"

Creditentials.SetCreditentials()
token = util.prompt_for_user_token(user, scope)
track = spotipy.Spotify(token).current_user_playing_track()
print(track)