Hey everyone! I’m working on a Python script that fetches currently playing content from Spotify. When I call the player endpoint, everything works fine for music tracks - I get all the song details in the item field. But when podcasts are playing, the item field comes back as null every single time.
def fetch_playback_data():
if time.time() > token_data.expiry_time:
print("Token expired, getting new one...")
update_token()
if not token_data.current_token:
print("Token refresh failed.")
return None, None, None, 0, 0
auth_headers = {"Authorization": f"Bearer {token_data.current_token}"}
playback_request = requests.get("https://api.spotify.com/v1/me/player", headers=auth_headers)
try:
json_data = playback_request.json()
print("API Response: -------- ", json_data)
except ValueError:
print("Response contains no JSON data.")
if playback_request.status_code == 200:
player_data = playback_request.json()
if player_data and player_data['is_playing']:
content_type = player_data.get('currently_playing_type')
current_item = player_data.get('item')
if content_type == 'track' and current_item:
song_id = current_item['id']
song_title = current_item['name']
performer = current_item['artists'][0]['name']
current_position = player_data['progress_ms']
total_length = current_item['duration_ms']
return song_id, song_title, performer, current_position, total_length
elif content_type == 'episode':
if current_item and 'id' in current_item:
podcast_id = current_item['id']
else:
context_data = player_data.get('context')
if context_data and 'uri' in context_data:
uri_string = context_data['uri']
if 'episode' in uri_string:
podcast_id = uri_string.split(':')[-1]
else:
print("URI doesn't have episode info.")
return None, None, None, 0, 0
else:
print("Missing context data for podcast.")
return None, None, None, 0, 0
episode_request = requests.get(f"https://api.spotify.com/v1/episodes/{podcast_id}", headers=auth_headers)
if episode_request.status_code == 200:
episode_data = episode_request.json()
episode_title = episode_data['name']
show_creator = episode_data['show']['publisher']
current_position = player_data['progress_ms']
total_length = episode_data['duration_ms']
return podcast_id, episode_title, show_creator, current_position, total_length
else:
print("Episode fetch failed. Error:", episode_request.text)
else:
print("Nothing is playing right now.")
else:
print("Playback request failed. Error:", playback_request.text)
return None, None, None, 0, 0
Has anyone found a reliable way to handle this issue? Any suggestions would be awesome!