KeyError: 'name' in Spotify Web API



我正在使用spotify的web API来获取歌曲信息,以便制作不和机器人。我在heroku上托管这个机器人。im使用tracks选项从歌曲ID中获取曲目名称和艺术家名称。当机器人在heroku上时,它会抛出以下错误:

https://pastebin.com/smqqqDfY

然而,当我在笔记本电脑上托管相同的代码时,它不会出现这样的错误。我甚至分离了spotify代码,看看JSON文件是否有一个名为"name"的密钥,它是否有效!

代码是:

#pulls the name and artist name from the API and link
def spotifypull(uri):
r = requests.get(spotify_base.format(id=uri), headers=headers)
r = r.json() 
return (r['name']+" "+r['artists'][0]['name'])
#checks if the link is a spotify link(this is from the "request" function)
if query.find("spotify") !=-1:
uri = query[31:53]
name = spotifypull(uri)

如果本地分离,则相同的代码给出正确的输出

import requests
query = "https://open.spotify.com/track/6WkrFOo6SGAjhGMrjIwAD4?si=VDwYLniGQLGmqzUK3RdBow"
uri = query[31:53]
SPOTIFY_ID = "<id>"
SPOTIFY_SECRET = "<secret>"
AUTH_URL = 'https://accounts.spotify.com/api/token'
ytbase = "https://www.youtube.com/watch?v="
auth_response = requests.post(AUTH_URL, {
'grant_type': 'client_credentials',
'client_id': SPOTIFY_ID,
'client_secret': SPOTIFY_SECRET,
})
auth_response_data = auth_response.json()
access_token = auth_response_data['access_token']
headers = {
'Authorization': 'Bearer {token}'.format(token=access_token)
}
spotify_base = 'https://api.spotify.com/v1/tracks/{id}'
r = requests.get(spotify_base.format(id=uri), headers=headers)
r = r.json()
name = r['name']+" "+r['artists'][0]['name']
print(name)

以上输出:

Wasn't Enough CrySpy

任何帮助都将不胜感激!如果需要,完整的代码在这里。

编辑:当在本地运行时,r.text是https://pastebin.com/sjrW3exWr.get_status为200

好吧,我遇到了问题,spotify代币在一个小时后到期。感谢@ygrorg的创意。

编辑:由于一些max brain mod希望我提供更多的清晰度,Spotify代币的有效期只有一个小时,我通过每次播放歌曲时调用一个新代币来解决这个问题。或者,只可能将令牌重新生成命令放入无限循环中,并在循环结束时延迟30-45分钟,这样每次都有一个新的令牌。

最新更新