English 中文(简体)
问题:我正在尝试使用python脚本暂停spotify播放
原标题:Issue: i m trying to pause spotify playing using a python script

我试图用这个python脚本来实现的是,在祈祷的时候阻止spotify播放,但它似乎从来没有起过作用,尽管我读了几十篇关于开发人员和chatgpt对话的spotify的文章,这就是我最终得到的:

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

注意:一般来说,我还是一个使用API和编码的初学者,但我对python和编码基础知识几乎无所不知。非常感谢。

。。。。。。。。。。。。。。。。。。。。。。。。。

问题回答

您需要在Spotify开发者Dash Board上设置重定向URI

https://developer.spotify.com/dashboard

并且需要设置范围

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

此处

此代码将起作用

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.





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签