You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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
    Use spotipy.util.prompt_for_user_token to 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 the SpotifyClientCredentials setup with the token you just retrieved.
  • Fetch the currently playing track
    Use sp.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 spotipy to update.
  • Handle edge cases: current_user_playing_track() returns None if the user isn't playing anything, so always add a check for that.

内容的提问来源于stack exchange,提问作者Jordan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:49:44