-1

What i'm trying to realise with this python script is to stop spotify from playing when it's prayer time , but it never seems to work although i read tens of article of dealing with spotify for developpers and conversations with chatgpt, this is what i ended up with:

import requests
import datetime
import geocoder
import time
import spotipy
from spotipy.oauth2 import SpotifyOAuth

# Set your Spotify app credentials (client ID and client secret)
client_id = 'YOUR_CLIENT_ID'
client_secret = 'YOUR_CLIENT_SECRET'
redirect_uri = 'YOUR_REDIRECT_URI'

def get_prayer_times(latitude, longitude):
    today = datetime.date.today()
    formatted_date = today.strftime('%Y-%m-%d')

    # Get the prayer times for today
    url = f"https://api.aladhan.com/v1/timings/{formatted_date}?latitude={latitude}&longitude={longitude}&method=2"
    response = requests.get(url)
    data = response.json()

    prayer_times = data['data']['timings']
    keys_to_remove = ['Sunrise', 'Sunset', 'Midnight', 'Imsak', 'Firstthird', 'Lastthird']

    # Remove unnecessary keys from the prayer times dictionary
    for key in keys_to_remove:
        prayer_times.pop(key, None)

    return prayer_times

def get_ip_address():
    response = requests.get('https://api.ipify.org?format=json')
    ip_data = response.json()
    ip_address = ip_data['ip']
    return ip_address

def get_latitude_longitude(ip_address):
    g = geocoder.ip(ip_address)
    if g.ok:
        latitude, longitude = g.latlng
        return latitude, longitude
    else:
        return None

def pause_spotify():
    devices = sp.devices()
    for device in devices['devices']:
        if device['is_active']:
            sp.pause_playback(device['id'])

def resume_spotify():
    devices = sp.devices()
    for device in devices['devices']:
        if device['is_active']:
            sp.start_playback(device['id'])

def main():
    ip_address = get_ip_address()
    location = get_latitude_longitude(ip_address)
    if location:
        latitude, longitude = location
        prayer_times = get_prayer_times(latitude, longitude)
        print("Prayer Times:")
        print(prayer_times)

        # Get current time
        current_time = datetime.datetime.now().strftime('%H:%M')

        for prayer, time_value in prayer_times.items():
            if current_time >= time_value:
                # Prayer time has passed
                print(f"{prayer} time has passed.")
                pause_spotify()
            else:
                # Prayer time has not yet arrived
                print(f"{prayer} time is yet to come.")
                resume_spotify()
                break

if __name__ == '__main__':
    auth_manager = SpotifyOAuth(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri)
    sp = spotipy.Spotify(auth_manager=auth_manager)
    main()

now i get how to get my client_id and client_secret from my spotifyfordeveloppers dashboard but i could never understand how i cant get that redirect uri although i read in some places that u can fill it with any spotify related link, but i always get the following error i couldn't solve: sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=client_id, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: Spotify.init() got an unexpected keyword argument 'auth_manager'

note: i'm still a beginner with using APIs and coding in generally but i know pretty much everything about python and coding basics. Thank you.

.........................

  • Do you really use `client_id` and `client_secret` like in the code above? To use Spotify API, you need to get a real client_id for yourself. The other problem is that Spotify API is meant to be used from Web-Applications only, as the user should be redirected to Spotify-Login page for logging in. So in general, a stand-alone python program will not work (without some dirty tricks....) – treuss Jun 26 '23 at 19:31
  • That error message is clear: the `Spotify` class does not expect to receive the `auth_manager` argument. So, why are you passing that argument? Did you get that code from some tutorial? – John Gordon Jun 27 '23 at 02:59
  • What i should i pass as a parameter then? I actually got that code from chatgpt but it seems valid and worked for that person who provided the answer – KhaliLounis Jun 27 '23 at 03:23
  • The code in the error message doesn't match your code. You should use the code [with user authentication](https://github.com/spotipy-dev/spotipy#with-user-authentication). – Ximzend Jun 27 '23 at 04:54

1 Answers1

0

You need to set up the Redirect URI at Spotify Developer Dash-Board

https://developer.spotify.com/dashboard

enter image description here

And needs to set up scopes

# scopes for Remote control playback, Get Available Devices, Pause playback
SCOPEs = ['app-remote-control', 'user-read-playback-state', 'user-modify-playback-state']

Detail information in here

This code will work

import requests
import datetime
import geocoder
import time
import spotipy
from spotipy.oauth2 import SpotifyOAuth

# Set your Spotify app credentials (client ID and client secret)
client_id = 'YOUR_CLIENT_ID'
client_secret = 'YOUR_CLIENT_SECRET'
redirect_uri = 'YOUR_REDIRECT_URI' # my demo use http://localhost:3000/callback

# scopes for Remote control playback, Get Available Devices, Pause playback
SCOPEs = ['app-remote-control', 'user-read-playback-state', 'user-modify-playback-state']

def get_prayer_times(latitude, longitude):
    today = datetime.date.today()
    formatted_date = today.strftime('%Y-%m-%d')

    # Get the prayer times for today
    url = f"https://api.aladhan.com/v1/timings/{formatted_date}?latitude={latitude}&longitude={longitude}&method=2"
    response = requests.get(url)
    data = response.json()

    prayer_times = data['data']['timings']
    keys_to_remove = ['Sunrise', 'Sunset', 'Midnight', 'Imsak', 'Firstthird', 'Lastthird']

    # Remove unnecessary keys from the prayer times dictionary
    for key in keys_to_remove:
        prayer_times.pop(key, None)

    return prayer_times

def get_ip_address():
    response = requests.get('https://api.ipify.org?format=json')
    ip_data = response.json()
    ip_address = ip_data['ip']
    return ip_address

def get_latitude_longitude(ip_address):
    g = geocoder.ip(ip_address)
    if g.ok:
        latitude, longitude = g.latlng
        return latitude, longitude
    else:
        return None

def pause_spotify():
    devices = sp.devices()
    for device in devices['devices']:
        if device['is_active']:
            sp.pause_playback(device['id'])

def resume_spotify():
    devices = sp.devices()
    for device in devices['devices']:
        if device['is_active']:
            sp.start_playback(device['id'])

def main():
    ip_address = get_ip_address()
    location = get_latitude_longitude(ip_address)
    if location:
        latitude, longitude = location
        prayer_times = get_prayer_times(latitude, longitude)
        print("Prayer Times:")
        print(prayer_times)

        # Get current time
        current_time = datetime.datetime.now().strftime('%H:%M')

        for prayer, time_value in prayer_times.items():
            if current_time >= time_value:
                # Prayer time has passed
                print(f"{prayer} time has passed.")
                pause_spotify()
                print(f"paused spotify song")
            else:
                # Prayer time has not yet arrived
                print(f"{prayer} time is yet to come.")
                resume_spotify()
                print(f"resumed spotify song")
                break

if __name__ == '__main__':
    auth_manager = SpotifyOAuth(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=SCOPEs)
    sp = spotipy.Spotify(auth_manager=auth_manager)
    main()

I captured a video (animation GIF). it shows to change from stopped to resume the song.

The left side is VS code to run the program, the right side is stopped in Spotify in Chrome. The song will resume, watch the green icon.

enter image description here

Bench Vue
  • 5,257
  • 2
  • 10
  • 14
  • i got some errors for the code u provided mainly concerned with the scopes thing and the way its made in the spotipy library (cant apply split method on list..) could u help me fix them, TypeError: Spotify.__init__() got an unexpected keyword argument 'auth_manager' self.scope=self._normalize_scope(scope) scopes = scope.split() also do i have to use spotify from the browser or the desktop app is enough ? edit: i actually fixed the split one through making SCOPEs a string with spaces, now i only got that authmanager error that i couldn't fix. – KhaliLounis Jun 27 '23 at 02:42
  • I tested again. it works in Windows 11 and Python `3.10.8`. I guess one item is possible. It is `spotipy` version. My installed `2.21.0`, you can check `pip show spotipy` or `pip freeze` from the terminal. Can you confirm your `spotipy` version? – Bench Vue Jun 27 '23 at 10:15
  • Also I checked `scope` parameter of `SpotifyOAuth` supports the list in git-hub source code in [here](https://github.com/spotipy-dev/spotipy/blob/master/spotipy/oauth2.py#L311) – Bench Vue Jun 27 '23 at 13:19
  • thank u for the fixes they actually worked, when i ran it i got redirected to an authorization link where i accepted something theni got shit ton of errors inthe terminal,although i set the redirect uri in my spotify dashboard to the one u provided but it doesnt work edit: here's what i get Prayer Times:{'Fajr': '03:55', 'Dhuhr': '12:41', 'Asr': '16:31', 'Maghrib': '20:00', 'Isha': '21:28'} Fajr time has passed. HTTP Error for PUT to https://api.spotify.com/v1/me/player/pause?device_id=(private) with Params: {} returned 403 due to Player command failed: Premium required (and more errors) – KhaliLounis Jun 27 '23 at 14:44
  • if works, can you vote me my answer? – Bench Vue Jun 27 '23 at 15:36
  • If 403 error, you needs to add `user-read-private` scope into SCOPEs – Bench Vue Jun 27 '23 at 15:39
  • i tried actually voting it when u just posted it but apparently i gotta reach 15 repuatations, also that scope thing didnt change anything,, i think the script only work for spotify premium users ( are u? ) – KhaliLounis Jun 27 '23 at 16:34
  • you can accept my answer by click up arrow(accept answer), it will give 10 points even if less you 15 points. – Bench Vue Jun 27 '23 at 16:47
  • I use paid spotify user not free user, I don't know it means premium user, Do you paid user? – Bench Vue Jun 27 '23 at 16:49
  • 1
    yeah paid is premium , personally i use free, now it makes sense thank you. – KhaliLounis Jun 27 '23 at 17:54
  • Thanks you for your accepting. – Bench Vue Jun 27 '23 at 18:18