dwlakes

Untitled

Apr 9th, 2022
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.26 KB | None | 0 0
  1. import random
  2. import requests
  3. import string
  4. import urllib
  5.  
  6.  
  7. class SpotifyClient(object):
  8.     def __init__(self, api_key):
  9.         self.api_key = api_key
  10.  
  11.     def get_random_tracks(self):
  12.         # %f%
  13.         wildcard = f'%{random.choice(string.ascii_lowercase)}%'
  14.         query = urllib.parse.quote(wildcard)
  15.         offset = random.randint(0, 2000)
  16.         url = f'https://api.spotify.com/v1/search?q={query}&offset={offset}&type=track'
  17.  
  18.         response = requests.get(
  19.             url,
  20.             headers={
  21.                 "Content-Type": "application/json",
  22.                 "Authorization": f"Bearer {self.api_key}"
  23.             }
  24.         )
  25.  
  26.         response_json = response.json()
  27.  
  28.         tracks = [track for track in response_json['tracks']['items']]
  29.  
  30.         print(f'Found {len(tracks)} from your search')
  31.  
  32.         return tracks
  33.  
  34.     def add_tracks_to_library(self, tracks_ids):
  35.         url = 'https://api.spotify.com/v1/me/tracks'
  36.  
  37.         response = requests.put(
  38.             url,
  39.  
  40.             headers={
  41.                 "Content-Type": "application/json",
  42.                 "Authorization": f"Bearer {self.api_key}"
  43.             },
  44.             json={
  45.                 'ids': tracks_ids
  46.             }
  47.         )
  48.  
  49.         return response.ok
  50.  
Advertisement
Add Comment
Please, Sign In to add comment