Search code examples
pythonspotipy

Spotipy high request rate


I'am currently working on a little program (mainly for myself) that will get my currently playing song and it will send it to a database so I can make some graphs to see how often I played an artist in X amount of time. To do this I have the following code:

import spotipy
import spotipy.util as util
from time import sleep

# My secret keys SO DON'T LEAK THEM
clientID = "CLIENT_ID"
clientSec = "CLIENT_SECRET"

while True:
    # The scopes defines how much you are allowed
    scope = "user-read-currently-playing"
    username = "USERNAME"   
    # Gets a token for spotify and should keep it updated
    token = util.prompt_for_user_token(username, scope, client_id=clientID, client_secret=clientSec, redirect_uri="http://localhost/Spotify/callback.php")
    sp = spotipy.Spotify(auth=token)    
    results = sp.currently_playing(market=None)

    progress = results["progress_ms"]
    playing = results["is_playing"]

    # Add the song after 15 seconds of playing
    if (progress >= 15000 and progress <= 15500 and playing):
        sendToDB()

    # Shows raw output that spotify returns
    print(results)
    sleep(0.4)

Every 0.4 seconds it will check if a song is within a time frame to see if there is a new song playing. ( I know it's a bad way but I haven't found a better way). But yesterday I saw on the spotify developer portal that 2 users total make about 300000 requests per day. I don't think that this is normal so I tried some different things to only call the util.prompt_for_user_token() when the token needed to be refreshed but the problem with that is that it will only return a new result when the token is refreshed. So I have two questions:

  1. Is there a better way for checking if there is a new song playing and,
  2. Is there a way to only request a new token every 30 minutes and still get live results from spotify?

Solution

  • There's also the Recently Played Tracks endpoint, which rather than get the single currently playing track, you can get the 50 most recently played tracks.

    Only the tracks listened to sufficiently long (I think 30 seconds) will be present on this endpoint (that's the threshold for Spotify to mark it as a play).

    Since you know a threshold for a play to count is 30 seconds, and the number of results the endpoint returns is 50, this means you only need to check about every 50 * 30 seconds to definitely capture all tracks listened to, every 25 minutes.