spotify.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """
  2. Spotify (Music)
  3. @website https://spotify.com
  4. @provide-api yes (https://developer.spotify.com/web-api/search-item/)
  5. @using-api yes
  6. @results JSON
  7. @stable yes
  8. @parse url, title, content, embedded
  9. """
  10. from json import loads
  11. from urllib import urlencode
  12. # engine dependent config
  13. categories = ['music']
  14. paging = True
  15. # search-url
  16. url = 'https://api.spotify.com/'
  17. search_url = url + 'v1/search?{query}&type=track&offset={offset}'
  18. embedded_url = '<iframe data-src="https://embed.spotify.com/?uri=spotify:track:{audioid}"\
  19. width="300" height="80" frameborder="0" allowtransparency="true"></iframe>'
  20. # do search-request
  21. def request(query, params):
  22. offset = (params['pageno'] - 1) * 20
  23. params['url'] = search_url.format(query=urlencode({'q': query}),
  24. offset=offset)
  25. return params
  26. # get response from search-request
  27. def response(resp):
  28. results = []
  29. search_res = loads(resp.text)
  30. # parse results
  31. for result in search_res.get('tracks', {}).get('items', {}):
  32. if result['type'] == 'track':
  33. title = result['name']
  34. url = result['external_urls']['spotify']
  35. content = result['artists'][0]['name'] +\
  36. " &bull; " +\
  37. result['album']['name'] +\
  38. " &bull; " + result['name']
  39. embedded = embedded_url.format(audioid=result['id'])
  40. # append result
  41. results.append({'url': url,
  42. 'title': title,
  43. 'embedded': embedded,
  44. 'content': content})
  45. # return results
  46. return results