Spotify api | my python script won't run when my Spotify app is turned off

Question:

I would like to make a script in python that retrieves what I’m listening to in real time on Spotify and allow me to send the information to an Arduino,
But the problem is that my script refuses to run when my Spotify is turned off, knowing that I have other information that passes between my PC and my Arduino and if the script does not run most of the functions I created on my Arduino does not work anymore
So I would like my script to work also when I don’t listen to music

Error : `

Traceback (most recent call last):
  File "C:UsershorvikAppDataLocalProgramsPythonPython310libsite-packagesrequestsmodels.py", line 971, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:UsershorvikAppDataLocalProgramsPythonPython310libjson__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:UsershorvikAppDataLocalProgramsPythonPython310libjsondecoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:UsershorvikAppDataLocalProgramsPythonPython310libjsondecoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:UsershorvikDesktopproject.py", line 62, in <module>
    serialDataToEncode = finishcpu + finishmem + get_current_track(ACCESS_TOKEN)
  File "C:UsershorvikDesktopDeskcompanionv1.py", line 25, in get_current_track
    json_resp = response.json()
  File "C:UsershorvikAppDataLocalProgramsPythonPython310libsite-packagesrequestsmodels.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

`

I tried to use other entries from the spotify api like ‘is_active’ or ‘is_playing’ by adding them in an if/else hoping that I could not go through "response.json()" but I understood that I had to go through this one
there’s probably something I’m missing that’s why I’m making this post
if someone can help me.

code :

import psutil
import serial
import requests
import time
from pprint import pprint


SPOTIFY_GET_CURRENT_TRACK_URL = 'https://api.spotify.com/v1/me/player/currently-playing'
ACCESS_TOKEN = 'i use token'

serial = serial.Serial()
serial.baudrate = 9600
serial.port = "COM5"
serial.open()

# spotify section

def get_current_track(access_token):
    response = requests.get(
        SPOTIFY_GET_CURRENT_TRACK_URL,
        headers={
            "Authorization": f"Bearer {access_token}"
        }
    )
    json_resp = response.json()

    if json_resp['is_playing'] == True :

        track_name = json_resp['item']['name']
        artists = [artist for artist in json_resp['item']['artists']]
        artist_names = ', '.join([artist['name'] for artist in artists])
        
        spotifytracksplaying = track_name + " By " + artist_names

    else :
        spotifytracksplaying = "you are not lisenting music"


    return spotifytracksplaying

while(1):
    # cpu and ram usage section
    cpu = psutil.cpu_percent(interval=1.2)
    mem = psutil.virtual_memory().percent

    if cpu < 10:
        finishcpu = "  " + str(cpu)
    elif cpu < 100:
        finishcpu = " " + str(cpu)
    else:
        finishcpu = str(cpu)

    if mem < 10:
        finishmem = "  " + str(mem)
    elif mem < 100:
        finishmem = " " + str(mem)
    else:
        finishmem = str(mem)

    # sending information
    serialDataToEncode = finishcpu + finishmem + get_current_track(ACCESS_TOKEN)
    serialDatatosend = serialDataToEncode.encode("UTF-8")

    serial.write(serialDatatosend)

    # Debugging
    #print(serialDatatosend)
    ##print(get_current_track(ACCESS_TOKEN))

serial.close()

Asked By: horvik

||

Answers:

You can catch JSONDecodeError if resource by url dont response correct json.

from json.decoder import JSONDecodeError

try:
    json_resp = response.json()
except JSONDecodeError:
    # Not json. No data. Return err.
Answered By: necro

Thank you very much for your quick response, it works!

Here is my code now :

def get_current_track(access_token):
response = requests.get(
    SPOTIFY_GET_CURRENT_TRACK_URL,
    headers={
        "Authorization": f"Bearer {access_token}"
    }
)
try:
    json_resp = response.json()
    track_id = json_resp['item']['id']
    track_name = json_resp['item']['name']
    artists = [artist for artist in json_resp['item']['artists']]
    link = json_resp['item']['external_urls']['spotify']
    artist_names = ', '.join([artist['name'] for artist in artists])
    spotifytracksplaying = track_name + " By " + artist_names

except:
    spotifytracksplaying = "No music played"


return spotifytracksplaying
Answered By: horvik
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.