使用Spotipy库调用currently_playing接口失败问题求助
Fixing Spotipy's
currently_playing Not Working Issue Hey Jordan, I see exactly what's going wrong here—let's get your current track retrieval up and running in no time!
The Core Problem
You're using the Client Credentials Flow (SpotifyClientCredentials) to authenticate with Spotify. This flow only grants access to public Spotify data (like artist info or public playlists), but it can't access user-specific private data like the currently playing track. The user-read-currently-playing scope requires the Authorization Code Flow, which links your app to a specific user account via their login.
Step-by-Step Fix
Here's how to adjust your code to use the correct authentication flow:
- Get a user-authorized token
Usespotipy.util.prompt_for_user_tokento trigger the user login flow. This will open a browser window for the user to grant your app permission to access their currently playing track. - Initialize Spotipy with the user token
Replace theSpotifyClientCredentialssetup with the token you just retrieved. - Fetch the currently playing track
Usesp.current_user_playing_track()instead of relying on the incorrect client setup.
Corrected Code
import json import spotipy import spotipy.util as util # Replace these with your actual credentials cid = "xxx" csecret = "xxx" redirectURI = "xxx" username = "xxx" scope = 'user-read-currently-playing' # Get user-authorized token token = util.prompt_for_user_token( username=username, scope=scope, client_id=cid, client_secret=csecret, redirect_uri=redirectURI ) if token: # Initialize Spotipy with the user token sp = spotipy.Spotify(auth=token) # Fetch currently playing track current_track = sp.current_user_playing_track() if current_track: # Print track details track_name = current_track['item']['name'] artist_name = current_track['item']['artists'][0]['name'] print(f"Currently playing: {track_name} by {artist_name}") else: print("No track is currently playing.") else: print("Could not retrieve token for user.")
Important Notes
- Double-check that your redirect URI in the code matches exactly what's set in your Spotify Developer Dashboard (under your app's settings). Mismatched URIs will cause authorization failures.
- Make sure you're using the latest version of Spotipy: run
pip install --upgrade spotipyto update. - Handle edge cases:
current_user_playing_track()returnsNoneif the user isn't playing anything, so always add a check for that.
内容的提问来源于stack exchange,提问作者Jordan
相关产品推荐
相关产品推荐

