Spotipy用户名无效?

时间:2017-10-22 21:41:07

标签: python spotify spotipy

对于我知道的流光,我有一个抽搐的机器人,我正在尝试制作一个命令,显示他目前在spotify上收听的歌曲。

我发现Spotipy库执行此操作,但我使用以下代码收到无效的用户名错误:

import spotipy
import spotipy.util as util

CLIENT_ID = 'xx'
CLIENT_SECRET = 'xx'

token = util.oauth2.SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)

cache_token = token.get_access_token()

sp = spotipy.Spotify(cache_token)
currentsong = sp.currently_playing()

print(currentsong)

在我的代码中,我填写了证书。所以这段代码给我发了这个错误:

Traceback (most recent call last):
  File "/Users/Pascalschilp/Documents/spot/spotipy-master/lol.py", line 13, in <module>
    currentsong = sp.currently_playing('spotify:user:passle')
  File "/Users/Pascalschilp/Documents/spot/spotipy-master/spotipy/client.py", line 899, in currently_playing
    return self._get("me/player/currently-playing", market = market)
  File "/Users/Pascalschilp/Documents/spot/spotipy-master/spotipy/client.py", line 148, in _get
    return self._internal_call('GET', url, payload, kwargs)
  File "/Users/Pascalschilp/Documents/spot/spotipy-master/spotipy/client.py", line 126, in _internal_call
    headers=r.headers)
spotipy.client.SpotifyException: http status: 404, code:-1 - https://api.spotify.com/v1/me/player/currently-playing?market=spotify%3Auser%3Apassle:
 Invalid username
[Finished in 1.2s with exit code 1]
[shell_cmd: python -u "/Users/Pascalschilp/Documents/spot/spotipy-master/lol.py"]
[dir: /Users/Pascalschilp/Documents/spot/spotipy-master]
[path: /usr/bin:/bin:/usr/sbin:/sbin]

我不确定为什么会出错。有人能指出我正确的方向吗?

此外/可替换地: 我怎样才能使用请求库来进行承载认证? (我试图在邮递员中手动执行请求并填写客户端ID,它给了我这个错误:“message”:“仅支持有效的承载认证”)

1 个答案:

答案 0 :(得分:1)

请勿使用此形式的授权。您遇到此问题的原因是您正在进行匿名API调用。此方法需要oAuth授权才能进行这些调用。设置用户名和适当的范围:

username = "myUsername"
scope = "user-read-currently-playing"

您需要申请人的重定向URI:

redirect_uri = "http://localhost:8888/callback/"

将令牌设为:

token = util.prompt_for_user_token(username, scope, CLIENT_ID, CLIENT_SECRET, redirect_uri)

现在您可以实例化Spotify对象。

sp = spotipy.Spotify(auth=token)

你应该从那里做起。将弹出一个窗口,提示您自己进行身份验证,但之后,将不再需要它,因为它将在缓存中。

如果你让它工作,你可以提取这样的数据:

song_name = currentsong['item']['name']
song_artist = currentsong['item']['artists'][0]['name']
print("Now playing {} by {}".format(song_name, song_artist))