def fit(self, user_id): ''' something really weird happening, number of artists collected from liza dropped from 400 to 308 with no changes in artist selection/deletion may have something to do with unicode? Should double check getting all playlists Should double check that unicode items are not being removed ie /x etc moving on to creating full pipeline ''' self.user_id = user_id self.token = util.prompt_for_user_token(user_id, scope = 'user-library-read', client_id = '530ddf60a0e840369395009076d9fde7', client_secret = 'd1974e81df054fb2bffa895b741f96f6', redirect_uri = 'https://github.com/bsbell21') print 'token created' self.s = sp.Spotify(auth = self.token) # new code start - getting playlist authentication self.token_playlist = util.prompt_for_user_token(user_id, scope = 'playlist-modify-public', client_id = '530ddf60a0e840369395009076d9fde7', client_secret = 'd1974e81df054fb2bffa895b741f96f6', redirect_uri = 'https://github.com/bsbell21') self.s_playlist = sp.Spotify(auth = self.token_playlist) self.s_playlist.trace = False # new code end #self.get_user_saved_tracks() -- old code user_playlists = self.get_user_public_playlists(user_id) df_pipeline, artist_data_echonest = self.get_playlist_data() return df_pipeline
def collect_playlist_data(username, user_playlists): """ Description: Collects and returns a list of track uri's extracted from the given user's playlist. (Duplicates allowed) Arguments: username: username of the playlist playlist_name: name of playlist from which to extract track uri's Example: username = '******' & user_playlists = ['coffee music', 'running'] """ # Getting token to access playlists token = util.prompt_for_user_token(username) if token: sp = spotipy.Spotify(auth=token) track_list = [] for playlist_name in user_playlists: pl_id = get_playlist_id(sp, username, playlist_name) if not (pl_id == None): pl = sp.user_playlist(username, pl_id) # get all tracks from playlist pl = get_playlist_tracks(sp, username, pl_id) track_list.extend(get_playlist_track_uris(pl)) else: print ("WARNING: No playlist by name \'%s \' for user \'%s\'\n" % (playlist_name, username)) return track_list else: print "Can't get token for", username return None
def createPlaylistForUser(utp): if len(utp.spotify_recommended_tracks) == 0: print("Missing recommended tracks. Early return") return if utp.username == "": print("Fail. Need to run Setup first. Early return.") return print( "Login to Spotify as %s" % utp.username ) scope = 'playlist-read-private user-top-read user-library-read playlist-modify-private playlist-modify-public' token = util.prompt_for_user_token(client_id=utp.clientId, client_secret=utp.clientSecret, redirect_uri=utp.redirect_uri, username=utp.username, scope=scope) if token: sp = spotipy.Spotify(auth=token) userId = sp.current_user()["id"] playlistsInitData = sp.user_playlist_create(userId, utp.createdPlaylistName) playlistId = playlistsInitData['id'] #print(utp.spotify_recommended_tracks) response = sp.user_playlist_add_tracks(user=userId, playlist_id=playlistId, tracks=utp.spotify_recommended_tracks[:50]) # TODO this reduction influences a lot #print(response) else: print("Can't get token for %s", utp.username)
def generate_spotify_playlist(tracks, playlist_name, username): """ Generates a Spotify playlist from the given tracks :param tracks: list of Track objects :param playlist_name: name of playlist to create :param username: Spotify username """ sp = spotipy.Spotify() formatted_tracks = [] for t in tracks: try: formatted_tracks.append(u'artist:"{artist}" track:"{track}"'.format(artist=t.artist, track=t.track)) except UnicodeDecodeError: pass search_res = [sp.search(q=t, type='track', limit=1) for t in formatted_tracks] track_ids = [(first(r.get('tracks', {}).get('items', {})) or {}).get('uri') for r in search_res if r.get('tracks', {}).get('items')] token = util.prompt_for_user_token(username, scope=scope, client_id=SPOTIFY_API_KEY, client_secret=SPOTIFY_API_SECRET, redirect_uri=SPOTIFY_URI) if token: sp = spotipy.Spotify(auth=token) sp.trace = False playlist = sp.user_playlist_create(username, playlist_name) if playlist and playlist.get('id'): sp.user_playlist_add_tracks(username, playlist.get('id'), track_ids) print "Playlist has been processed." else: print "Can't get token for", username
def generate_spotify_playlist(tracks, playlist_name, username): """ Generates a Spotify playlist from the given tracks :param tracks: list of Track objects :param playlist_name: name of playlist to create :param username: Spotify username """ sp = spotipy.Spotify() formatted_tracks = [u'artist:"{artist}" track:"{track}"'.format(artist=t.artist, track=t.track) for t in tracks] search_res = [sp.search(q=t, type='track', limit=1) for t in formatted_tracks] track_ids = [(first(r.get('tracks', {}).get('items', {})) or {}).get('uri') for r in search_res if r.get('tracks', {}).get('items')] token = util.prompt_for_user_token(username, scope=scope) if token: sp = spotipy.Spotify(auth=token) sp.trace = False playlist = sp.user_playlist_create(username, playlist_name) if playlist and playlist.get('id'): sp.user_playlist_add_tracks(username, playlist.get('id'), track_ids) print "boom!" else: print "Can't get token for", username
def make_playlist(username, playlistName="Spoons&Tunes", genre="rock", location="Boston,MA", numSongs=20): scope = 'playlist-modify-public' token = util.prompt_for_user_token(username, scope,"2a1cd7b9a1ee4294b4085e52d2ac51a2", "e771e11a11f9444c906f6eccabf3a037","http://google.com") songList = Music.getPlayList(genre, location, numSongs) spotify = spotipy.Spotify(auth=token) curlist = spotify.user_playlist_create(username,playlistName, public=True) songIDs = [] for song in songList: #print song songDict = spotify.search(q='track:'+song.__str__(),limit=1,type='track') for i, t in enumerate(songDict['tracks']['items']): songIDs.append( t['external_urls']['spotify']) break #songDict = song.get_tracks('spotify-WW')[0] #id = songDict['foreign_id'] #songIDs.append(id[14:]) #print len(songIDs) spotify.user_playlist_add_tracks(username, curlist['id'], songIDs) return curlist['external_urls']['spotify']
def favSpotifyArtists(): shortArtists, medArtists, longArtists = [], [], [] if len(sys.argv) > 1: username = sys.argv[1] else: print("Usage: %s username" % (sys.argv[0],)) sys.exit() scope = 'user-top-read' token = util.prompt_for_user_token(username, scope) if token: sp = spotipy.Spotify(auth=token) sp.trace = False ranges = ['short_term', 'medium_term', 'long_term'] for range in ranges: #print "range:", range results = sp.current_user_top_artists(time_range=range, limit=50) for i, item in enumerate(results['items']): #print i, item['name'] name = item['name'] if name == 'short_term': shortArtists.append(name.encode("utf-8")) return shortArtists elif name == 'medium_term': medArtists.append(name.encode("utf-8")) return medArtists else: longArtists.append(name.encode("utf-8")) return longArtists print else: print("Can't get token for", username)
def fit(self, user_ids, update = []): ''' INPUT: list of user_ids, list of user_ids to update OUTPUT: DataFrame with listen data for all users' public playlists if update, will delete user data from database and repopulate it, else will look for data in database and use that if it exists ''' #adding this as fix but want to remove self.token = util.prompt_for_user_token(self.my_id, scope = 'playlist-modify-public user-library-read playlist-read-private playlist-modify-private user-library-modify', client_id = '530ddf60a0e840369395009076d9fde7', client_secret = 'd1974e81df054fb2bffa895b741f96f6', redirect_uri = 'https://github.com/bsbell21') # remove above when you figure out expiration df_pipeline_list = [] for user_id in user_ids: if user_id in update: df_pipeline_user = self.fit_one(user_id, update = True) else: df_pipeline_user = self.fit_one(user_id) if len(df_pipeline_user) > 0: df_pipeline_list.append(df_pipeline_user) df_pipeline_full = pd.concat(df_pipeline_list)#.reset_index() return df_pipeline_full
def enumerate_playlists(username): scope = 'user-library-modify playlist-read-collaborative playlist-read-private' token = util.prompt_for_user_token(username=username, redirect_uri='http://localhost:8888/callback', scope=scope) if token: sp = spotipy.Spotify(auth=token) playlists = sp.user_playlists(username) for playlist in playlists['items']: if playlist['owner']['id']: print() print(playlist['name']) print(' total tracks', playlist['tracks']['total']) save_input = sync_playlist(playlist['name']) if save_input == 'Y' or save_input == 'y': results = sp.user_playlist(username, playlist['id'], fields="tracks,next") tracks = results['tracks'] j = 0 track_ids = [] for i, item in enumerate(tracks['items']): track = item['track'] if j == 50: sp.current_user_saved_tracks_add(track_ids) track_ids.clear() j = 0 track_ids.append(track['id']) j += 1 sp.current_user_saved_tracks_add(track_ids) else: print("Can't get token for", username)
def show_tracks(results): for i, item in enumerate(tracks['items']): track = item['track'] print (" %d %32.32s %s" % (i, track['artists'][0]['name'], track['name'])) if __name__ == '__main__': if len(sys.argv) > 1: username = sys.argv[1] else: print ("Need your username!") print ("usage: python user_playlists.py [username]") sys.exit() token = util.prompt_for_user_token(username) if token: sp = spotipy.Spotify(auth=token) playlists = sp.user_playlists(username) for playlist in playlists['items']: if playlist['owner']['id'] == username: print (playlist['name']) print (' total tracks', playlist['tracks']['total']) results = sp.user_playlist(username, playlist['id'], fields="tracks,next") tracks = results['tracks'] show_tracks(tracks) while tracks['next']: tracks = sp.next(tracks) show_tracks(tracks) else: print ("Can't get token for", username)
def handle(self, *args, **options): username = options['username'] try: user = User.objects.get(username=username) except User.DoesNotExist: raise CommandError(u'User with username "{}" does not exist'.format(username)) spotify_user = options['spotify_username'] token = util.prompt_for_user_token(spotify_user, scope='playlist-read-private user-library-read user-follow-read') self.sp = spotipy.Spotify(auth=token) artists = set() artists.update(self.get_playlist_artists(spotify_user)) artists.update(self.get_library_artists()) artists.update(self.get_followed_artists()) artists.discard('') for artist in artists: try: artist_obj = Artist.objects.get(name__iexact=artist) except Artist.DoesNotExist: artist_obj = Artist.objects.create(name=artist) ArtistRating.objects.get_or_create(artist=artist_obj, user=user, defaults={'rating': ArtistRating.RATING_UNRATED})
def _get_auth(self): return spotipy_util.prompt_for_user_token( username=self.username, client_id=self.client_id, client_secret=self.client_secret, redirect_uri='http://example.com/tunezinc/', scope=self.SCOPES, )
def command_token(args): token = util.prompt_for_user_token(args.username) if token: print token with open(os.path.expanduser('~/.playa'), 'w') as f: f.write(json.dumps({'token': token})) else: print "Can't get token for", args.username
def get_token(self): scope = 'playlist-modify-private' return util.prompt_for_user_token( SPOTIFY_AUTH['USERNAME'], scope, client_id=SPOTIFY_AUTH['CLIENT_ID'], client_secret=SPOTIFY_AUTH['CLIENT_SECRET'], redirect_uri=SPOTIFY_AUTH['REDIRECT_URI'])
def get_token(username, scope): """Obtain an access token for the user.""" token = util.prompt_for_user_token( username=username, scope=scope, client_id=os.environ['SPOTIPY_CLIENT_ID'], client_secret=os.environ['SPOTIPY_CLIENT_SECRET'], redirect_uri=os.environ['SPOTIPY_REDIRECT_URI']) return token
def _get_token(self, scope): token = util.prompt_for_user_token(self.username, scope=scope, client_id=self.ws_key, client_secret=self.ws_secret, redirect_uri=self.redirect_uri) if not token: raise RuntimeError("Cannot get token for user %s" % self.username) return token
def __init__(self): self.user_saved_tracks = None self.m = msd.MSD_Queries() self.artist_data_echonest = None self.my_id = '1248440864' # will always use my id self.token = util.prompt_for_user_token(self.my_id, scope = 'playlist-modify-public user-library-read playlist-read-private playlist-modify-private user-library-modify', client_id = '530ddf60a0e840369395009076d9fde7', client_secret = 'd1974e81df054fb2bffa895b741f96f6', redirect_uri = 'https://github.com/bsbell21') self.s = sp.Spotify(auth = self.token)
def get_connection(username, redirect_uri): token = util.prompt_for_user_token(username, SPOTIPY_SCOPE, client_id=SPOTIFY_CLIENT_ID, client_secret=SPOTIFY_CLIENT_SECRET, redirect_uri=redirect_uri) if token: return spotipy.Spotify(auth=token) else: return spotipy.Spotify()
def seed(request): token = util.prompt_for_user_token(steve_spotify_id, 'playlist-modify-public') sp = spotipy.Spotify(token) playlists = sp.user_playlists(steve_spotify_id, limit=50)['items'] for p in playlists: print p Playlist.objects.create(spotify_id=p['id'], user_id=steve_spotify_id, name=p['name']) return HttpResponse("seeded with steves playlists")
def spotifysubmit(songlist): timestamp = datetime.datetime.now().strftime("%Y-%m-%d ") logfile = '/var/log/risk-radio.log' # Sets permissions for this application. # A list of available scopes can be found at: # https://developer.spotify.com/web-api/using-scopes/ scope = 'user-library-read playlist-modify playlist-read-private playlist-modify-private' # To set username, run this from bash: # export SPOTIPY_USERNAME='******' username = os.getenv('SPOTIPY_USERNAME') token = util.prompt_for_user_token(username, scope) # To set the playlist, run this from bash: # export SPOTIPY_RISK_PLAYLIST='playlistid' # You can see the playlist id by looking at the URL: # https://play.spotify.com/user/USERNAME/playlist/PLAYLISTID playlist_id = os.getenv('SPOTIPY_RISK_PLAYLIST') if token: # Authenticate yourself with oauth2 sp = spotipy.Spotify(auth=token) # Since this funciton will only be run if there is an update, update the log file. f = open(logfile, 'a') f.write(timestamp + "Feed updated\n") f.close for song in songlist: try: songids = [] if not song: break # Search for the song on spotify # Make sure we are searching for a track instead of an artist or album results = sp.search(song, type='track') # Get the track id of the song spotifyuri = results['tracks']['items'][0]['id'] # Add the track id to the songids object songids.append(spotifyuri) # trace is set to False for silent submission. # Set to True for verbose output sp.trace = False # Actually add the song to the playlist addtolist = sp.user_playlist_add_tracks(username, playlist_id, songids) # Update the log file saying that the song was found and added f.write("Successfully added: " + song + "\n") f.close except: # Some of the songs on Risk are not on spotify # If a song can't be found, record it to the log f.write("Song not found: " + song + "\n") f.close else: print "Can't get token for", username
def create_client(): username = '******' scope = 'user-library-read' client_id = '8c02fc8f22344a06b1f2ca8b61efef30' client_secret = 'ae68ed70bf7445578e3e9fbb224e2292' redirect_uri = 'http://localhost:8888/callback' token = util.prompt_for_user_token(username, scope, client_id, client_secret, redirect_uri) Client = spotipy.client.Spotify(auth=token) return Client
def authSpotify(self): # Too lazy to figure out which scopes are actually needed, so ask for all of them. scope = "playlist-read-private playlist-read-collaborative playlist-modify-public playlist-modify-private streaming user-follow-modify user-follow-read user-library-read user-library-modify user-read-private user-read-birthdate user-read-email" clientId = "9e41ff3d50b54cceaf24cfcf38ea2857" clientSecret = "e9acd3ff114043a8b7facd313a842077" # scope = urllib.quote(scope) token = util.prompt_for_user_token(self.spotifyUsername, scope, clientId, clientSecret, "http://localhost") self.spotify = spotipy.Spotify(auth=token)
def spotify_refresh(self): token = util.prompt_for_user_token(self.spotify_data['username'], self.spotify_data['scope'], self.spotify_data['client_id'], self.spotify_data['client_secret'], self.spotify_data['redirect_uri']) if token: self.spotify_data['token'] = token else: self.send( self.channel, "Can't get token", message_type="groupchat" )
def add_tracks(username, playlist_id, track_ids): chosen_scope = 'playlist-modify-private' token = util.prompt_for_user_token(username, scope = chosen_scope, client_id = spotipy_client_id, client_secret = spotipy_client_secret, redirect_uri = spotipy_redirect_url) if token: sp = spotipy.Spotify(auth = token) sp.trace = True public = False sp.user_playlist_add_tracks(username,playlist_id, track_ids) else: print("Can't get token for", username)
def auth_flow(user_scope): creds = get_creds() try: token = util.prompt_for_user_token('ramrom23', client_id=creds['client_id'], scope=user_scope, client_secret=creds['client_secret'], redirect_uri='http://github.com/ramrom') #client_secret='blah', redirect_uri='http://github.com/ramrom') except spotipy.oauth2.SpotifyOauthError: print('Oauth error!') sys.exit(1) return token
def __get_token(self): token = util.prompt_for_user_token( self.username, self.scope, self.client_id, self.client_secret, self.redirect_uri ) if token: return spotipy.Spotify(auth=token)
def query_spotify(username, output_file): scope = 'user-library-read' token = util.prompt_for_user_token(username=username, scope=scope, client_id=ID, client_secret=SECRET, redirect_uri=RD_URI) if token: tracks = get_tracks(token, -1) lines = map(transform_tracks, tracks) UTF8Writer(open(output_file, 'w')).write("\n".join(lines)) else: print "Can't get token for", username
def __init__(self, proposer = Proposer(), chooser = Chooser()): self.proposer = proposer self.chooser = chooser with open("keys.json") as file_open: keys = json.load(file_open) scope = 'playlist-modify-public' token = util.prompt_for_user_token(keys["username"], scope) self.sp = spotipy.Spotify(auth=token) self.playlist = self.sp.user_playlist_create("jakecoltman", "PartyTime - {0}".format(datetime.now().isoformat())) self.id = self.playlist["id"]
def _spotipyconnect(): import spotipy import spotipy.util as sputil scope = 'playlist-modify-public' args = dict(client_id=getSpotifyClientID(), client_secret=getSpotifyClientSecret(), redirect_uri=getSpotifyCallbackUrl()) if scope: args['scope'] = scope token = sputil.prompt_for_user_token(getSpotifyUsername(), **args) return spotipy.Spotify(auth=token)
import os import sys import json import spotipy import webbrowser import spotipy.util as util from json.decoder import JSONDecodeError # Get username from terminal username = sys.argv[1] # User Id: 123181425 # Erase cache and prompt for user permission try: token = util.prompt_for_user_token(username) except: os.remove(f".cache-{username}") token = util.prompt_for_user_token(username) # Create our spotipyObject spotipyObject = spotipy.Spotify(auth=token) user = spotipyObject.current_user() displayName = user['display_name'] followers = user['followers']['total'] while True: print() print('>>> Welcome to Spotipy ' + displayName + '!')
def item_track_ids(items): """Return track id from JSON.""" return {it['track']['id'] for it in items} def to_timestamp(date): """Convert string to UNIX timestamp.""" ts = datetime.strptime(date, '%Y-%m-%dT%H:%M:%SZ').timestamp() return ts scope = 'playlist-modify-public user-library-read' username = sys.argv[1] playlist_length = sys.argv[2] token = util.prompt_for_user_token(username, scope, client_id=credentials.client_id, client_secret=credentials.client_secret, redirect_uri=credentials.redirect_uri) sp = spotipy.Spotify(auth=token) # Create playlist if it does not exist pl_name = 'Recently liked' playlists = get_playlists(sp, username) if pl_name not in playlists: sp.user_playlist_create(username, pl_name) playlists = get_playlists(sp, username) playlist_id = playlists[pl_name] # Fetch songs and update playlist liked_songs = sorted_id(get_n_last_liked(sp, playlist_length)) playlist_songs = item_track_ids(sp.user_playlist(username, playlist_id)['tracks']['items']) if not set(liked_songs) == playlist_songs:
secret = '<INSERT CLIENT SECRET HERE>' # Client Secret; copy this from your app username = '******' # Your Spotify username CACHE = '.cache-' + username # for avaliable scopes see https://developer.spotify.com/web-api/using-scopes/ scope = 'user-library-read playlist-modify-public playlist-read-private' redirect_uri = 'http://localhost:8080' # Paste your Redirect URI here client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret) sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) token = util.prompt_for_user_token(username=username, scope=scope, client_id=cid, client_secret=secret, redirect_uri=redirect_uri, cache_path=CACHE) if token: sp = spotipy.Spotify(auth=token) else: print("Can't get token for", username) sourcePlaylistID = '<INSERT PLAYLIST-ID>' sourcePlaylist = sp.user_playlist(username, sourcePlaylistID) tracks = sourcePlaylist["tracks"] songs = tracks["items"] track_ids = [] track_names = []
import os from sqlalchemy import create_engine import sqlalchemy.types import spotipy import spotipy.util as util import seaborn as sns os.environ['SPOTIPY_CLIENT_ID'] = '00b7317977ad4c0d971af8274f1aa790' os.environ['SPOTIPY_CLIENT_SECRET'] = '6efbf45fe72d435f9739d0c0f4c26db5' os.environ['SPOTIPY_REDIRECT_URI'] = 'https://360i.com/' base_url = 'https://api.spotify.com' scope = 'playlist-read-private' # spotify:playlist: rap_caviar = '37i9dQZF1DX0XUsuxWHRQd' engine = create_engine('sqlite:///playlist_RC.db', echo=False) conn = engine.connect() token = util.prompt_for_user_token('Puffer Fish', scope=scope) sp = spotipy.Spotify(auth=token) playlists = sp.user_playlists('spotify') df_tracks = pd.DataFrame( columns=['name', 'popularity', 'duration_ms', 'artist_name']) df_artists = pd.DataFrame( columns=['id', 'a_name', 'a_popularity', 'followers', 'tracks']) for playlist in playlists['items']: if rap_caviar in playlist['id']: print('total songs:', playlist['name'], 'are', playlist['tracks']['total']) tracks = sp.playlist_tracks( playlist['id'], fields= 'items.track.name, items.track.artists, items.track.duration_ms,items.track.popularity',
import spotipy.util as util import credentials input("ENTER to start") for i in range(10, 0, -1): print(i) time.sleep(1) # State of Phone: 0->Not lifted, 1->Lifted state = 1 # Set up for Spotipy token = util.prompt_for_user_token( 'moaromnoms', scope='user-modify-playback-state user-read-playback-state', client_id=credentials.c_id, client_secret=credentials.c_secret, redirect_uri='http://localhost/') sp = spotipy.Spotify(auth=token) # Spotipy select device d_list = sp.devices()['devices'] d_id = d_list[0]['id'] # Main Loop while True: try: # Get Arduino Data info = requests.post("http://127.0.0.1:8080/serial.dat").content if not info: continue
import googleapiclient.errors scope = 'user-library-read user-library-modify user-read-playback-state playlist-read-private playlist-modify-private' # Spotify Scopes scopes = ['https://www.googleapis.com/auth/youtube.readonly'] # YouTube Scopes if len(sys.argv) > 1: username = sys.argv[1] else: print("Usage: %s username" % (sys.argv[0], )) sys.exit() CLIENT_ID = 'YOUR CLIENT ID' CLIENT_SECRET = 'YOUR CLIENT SECRET' REDIRECT_URI = 'http://localhost:8888/callback' token = util.prompt_for_user_token(username, scope, CLIENT_ID, CLIENT_SECRET, REDIRECT_URI) if token: sp = spotipy.Spotify(auth=token) saved_tracks = sp.current_user_saved_tracks() playlists = sp.current_user_playlists() os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' api_service_name = 'youtube' api_version = 'v3' client_secrets_file = r"PATH TO JSON FILE" flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file( client_secrets_file, scopes) credentials = flow.run_console()
#hello! #spotify authentication cid ='d874f49748c84696b9015d3c3d1bbcae' # Client ID; copy this from your app secret = 'ba49882c11ff438592008d35c3add538' # Client Secret; copy this from your app username = '******' # Your Spotify username scope = 'user-library-read playlist-modify-public playlist-read-private' redirect_uri='http://localhost/' # Paste your Redirect URI here client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret) sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) token = util.prompt_for_user_token(username, scope, cid, secret, redirect_uri) if token: sp = spotipy.Spotify(auth=token) else: print("Can't get token for", username) #get tracks and saves as resutls os.system('curl -o seed.json -X "GET" "https://api.spotify.com/v1/recommendations?limit=10&market=US&seed_genres=country" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer '+token+'"') batcmd="cat seed.json | grep 'spotify:track' | sed 's/ \"uri\" : \"spotify:track://g' | sed 's/\"//g'" new = subprocess.check_output(batcmd, shell=True) results = new.split("\n") print(results) results.pop()
import os import sys import json import spotipy import webbrowser import spotipy.util as util from json.decoder import JSONDecodeError # Get the username from terminal username = sys.argv[1] scope = 'user-read-private user-read-playback-state user-modify-playback-state' # Erase cache and prompt for user permission try: token = util.prompt_for_user_token(username, scope) # add scope except (AttributeError, JSONDecodeError): os.remove(f".cache-{username}") token = util.prompt_for_user_token(username, scope) # add scope # Create our spotify object with permissions spotifyObject = spotipy.Spotify(auth=token) # Get current device devices = spotifyObject.devices() deviceID = devices['devices'][0]['id'] # Current track information track = spotifyObject.current_user_playing_track() artist = track['item']['artists'][0]['name'] track = track['item']['name']
# Shows the top artists for a user import sys import spotipy import spotipy.util as util if len(sys.argv) > 1: username = sys.argv[1] else: print("Usage: %s username" % (sys.argv[0],)) sys.exit() scope = 'user-top-read' token = util.prompt_for_user_token(username, scope, redirect_uri='http://localhost') if token: sp = spotipy.Spotify(auth=token) sp.trace = False ranges = ['short_term', 'medium_term', 'long_term'] for range in ranges: print("range:", range) results = sp.current_user_top_artists(time_range=range, limit=50) for i, item in enumerate(results['items']): print(i, item['name']) print() else: print("Can't get token for", username)
if underTheRadar == None or underTheRadar == "No Gig": eventFinda = getEventFinda(search, artist) if eventFinda == None: print("UnderTheRadar") print("Page not found") return None elif eventFinda == "No Gig": return None else: return search+"\n"+eventFinda else: return search+"\n"+underTheRadar #set up authentication #Need to go to https://developer.spotify.com/ and sign up to receive a client ID and client Secret token = util.prompt_for_user_token(username='******',scope='user-follow-read',client_id='Replace with client ID',client_secret='Replace with client ID',redirect_uri='https://www.google.com/') spotify = spotipy.Spotify(auth=token) #initialise variables listArtists = [] artists = spotify.current_user_followed_artists(limit=50); #iterate till at the end to get around the 50 limit while artists['artists']['items']!=[]: for key in artists['artists']['items']: #gets name of each artist and splits it into words data = key['name'] words = data.split() listArtists.append(words) #checks if last artist if key == artists['artists']['items'][-1]:
plt.xticks(fontsize=14) # Inserting code here to create xlabel & ylabel, and make the size bigger plt.ylabel('Valence', fontsize=16) plt.xlabel('Energy', fontsize=16) # Here, we are reading the CSV file(consist of set of songs) data = ascii.read("song-list.csv") Artists = data['Artist'] Songname = data['Title'] # Inserting code for authorisation scope = 'user-library-read' token = util.prompt_for_user_token( "pjoshi3", scope, client_id='3df26298e5ce4b969fa1282a2cb3965e', client_secret='add8a85b252945b48817511be0f00efc', redirect_uri='https://www.google.com/') spotify = spotipy.Spotify(token) # Here, we made a blank list of track,energy,valence for further storing of data Track = [] Energy = [] Valence = [] # For loop, to get the values of Energy & Valence for i in range(0, len(Songname)): #Inserting code to check the song in spotify & then to get the id of every song results = spotify.search(q='track:' + Songname[i], type='track') items = results['tracks']['items']
import spotipy import spotipy.util as util from settings_local import SPOTIFY_USERNAME, SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, \ SPOTIFY_REDIRECT_URI, SPOTIFY_PLAYLIST_ID, SPOTIFY_SCOPE token = util.prompt_for_user_token(SPOTIFY_USERNAME, SPOTIFY_SCOPE, client_id=SPOTIFY_CLIENT_ID, client_secret=SPOTIFY_CLIENT_SECRET, redirect_uri=SPOTIFY_REDIRECT_URI)
from spotipy.oauth2 import SpotifyClientCredentials clientid = "97b72e4133f3495c88c50016f4ac3347" secret = "3bb3891a7a68420a817cdd9a5a2a5552" username = "******" client_cred_manager = SpotifyClientCredentials(client_id=clientid, client_secret=secret) model = spotipy.Spotify(client_credentials_manager=client_cred_manager) scope = 'user-library-read playlist-read-private' #token = "Bearer BQBHbEieVIBtDz5QcD3M6LxfWXcscBYd7ZzStDjP_3wKHkEFjY4QqFV-82EcU-wNvBo_Fnawc7JMx9KDLx1WdaWj2gojr5RGZguzsyEPg5RkkBPLDbnum850dZ4e_xRu41DOWsfZWNBq1tlfzDkRF1j3SgPAs-0zFut3WCoj&refresh_token=AQCPILw9Y6szk_KjqSVIHueizz-AU4iEPZ2SnkxLhTjtlPgI3l0eh8As9tEcmq3RJoqEMYceU71bA-jeUeYWnUOo5WZCNgq9IQUB9CqPR0OwFwJUInJFNVuncqKeU6yddAY" token = util.prompt_for_user_token( username, scope, client_id=clientid, client_secret=secret, redirect_uri="https://rachitmishra25.com/callback/") if token: model = spotipy.Spotify(auth=token) else: print("unable to get token for:", username) ## defining playlists #playlist1 https://open.spotify.com/user/rachit.mishra94/playlist/1VzO6phA696s1CRvzMCgbQ hiphop_playlist = model.user_playlist("rachit.mishra94", "1VzO6phA696s1CRvzMCgbQ") other_playlist = model.user_playlist("fh6g7k0xv9nim7jbewm42in21", "4UMMRDG0FyMV0IDAeoFJza")
if tag != None: return '{} - {}'.format(tag[0], tag[1]) else: return ' ' def donothing(): filewin = Toplevel(root) button = Button(filewin, text="Do nothing button") button.pack() if __name__ == "__main__": token = util.prompt_for_user_token( username, scope, client_id='**************', client_secret='************', redirect_uri='http://example.com/callback/') ''' if token: sp = spotipy.Spotify(auth=token) user_playlists = get_user_playlists() while True: print '1.Sort a playlist' print '2.Add a tag' function = input('Choose a function') for i, user_playlist in enumerate(user_playlists): print("{} : {}".format(i, user_playlist.playlist_name)) chosen_playlist = input('Choose a playlist: ') if function == 1:
if __name__ == '__main__': # retrieve songs and playlists from Google Music library gm_songs, gm_playlists = gm_get_music() # get users' spotify username username = input("Spotify username: ") # generate spotify token and add music/playlists SPOTIPY_CLIENT_ID = '' SPOTIPY_CLIENT_SECRET = '' SPOTIPY_REDIRECT_URI = '' scope = 'user-library-modify user-library-read playlist-modify-private playlist-read-private' token = util.prompt_for_user_token(username, scope, client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET, redirect_uri=SPOTIPY_REDIRECT_URI) if token: sp = spotipy.Spotify(auth=token) sp.trace = False # parses gm music into albums and individual tracks, adds them to spotify, and returns any # tracks that couldn't be found in spotify invalid_tids = sp_add_gm_music(gm_songs, username, sp) # build spotify playlists from playlists retrieved from gm sp_add_gm_playlists(gm_playlists, username, sp) # print out which songs couldn't be added
def authenticate(): """Authenticates you to Spotify """ scope = 'user-library-read' username = '' return util.prompt_for_user_token(username, scope)
if songs_df.empty: songs_df = df3 else: songs_df = pd.concat([songs_df,df3],axis=0,ignore_index=True) return songs_df user_name = st.text_input("Please enter you Spotify username") st.write("You can fetch your username by checking your account details on https://www.spotify.com/us/account/overview/") if(user_name): uri_list = st.text_input("Please enter the URI of the Spotify song/playlist you want labeled") st.write("You can learn how to obtain the URI by checking out: http://help.playlistpush.com/en/articles/2511141-how-do-i-find-my-spotify-uri-link") if(st.button('Click here to login into your Spotify account')): token = util.prompt_for_user_token(user_name, scope,client_id=cid, client_secret=secret, redirect_uri=redirect_uri) if token: #print("Worked") sp = spotipy.Spotify(auth=token) current_user = sp.current_user() username = current_user["display_name"] playlists = sp.user_playlists(username) playlist_uris = [] playlist_labels = {} count=0 for playlist in playlists['items']: pl_name = playlist['name'] playlist_uris.append(playlist["id"]) playlist_labels[pl_name] = count print("Playlist name: {}".format(pl_name)) count+=1
import spotipy import spotipy.util as util def show_tracks(track_list): for i, item in enumerate(track_list['items']): track = item['track'] print(" %d %32.32s %s" % (i, track['artists'][0]['name'], track['name'])) username = '******' token = util.prompt_for_user_token(username, 'user-library-read') #token = util.prompt_for_user_token(username,scope,client_id='0ffe4f5e083f464f8ad6061cd80785ca',client_secret='e1c15024a0c744a792d729510575a0ca',redirect_uri='http://ec2-18-191-18-199.us-east-2.compute.amazonaws.com/') if token: sp = spotipy.Spotify(auth=token) playlists = sp.user_playlists(username) for playlist in playlists['items']: if playlist['owner']['id'] == username: print(playlist['name']) print(' total tracks', playlist['tracks']['total']) results = sp.user_playlist(username, playlist['id'], fields="tracks,next") tracks = results['tracks'] show_tracks(tracks) while tracks['next']: tracks = sp.next(tracks) show_tracks(tracks) else: print("Can't get token for", username)
def get_token(username, scope, client_id, client_secret): return util.prompt_for_user_token(username, scope, client_id, client_secret, redirect_uri='http://localhost/')
import os import sys import json import spotipy import spotipy.util as util from json.decoder import JSONDecodeError username = '******' scope = 'user-library-read' token = util.prompt_for_user_token(username,scope,client_id='96a71a9efaa84bb0811f793c02bf7cba',client_secret='36693ddccae24cfcb852ff5bb74a9c53',redirect_uri='https://www.google.com/') spotify = spotipy.Spotify(auth=token) results = spotify.featured_playlists(locale=None, country=None, timestamp=None, limit=20, offset=0) # results = spotify.categories(locale=None, country=None, limit=30, offset=0) print('\nMessage: ', results['message']) for playlist in results['playlists']['items']: print('Playlist') for key in playlist: print('\t', key, '->', playlist[key]) description = playlist['description'] name = playlist['name'] # print(key, ': ', value) # albums = results['items'] # while results['next']:
top_10tracks_uri = [] for artist in top_artists_uri: top_tracks_all = sp_auth.artist_top_tracks(artist) top_tracks = top_tracks_all['tracks'] for track_data in top_tracks: top_10tracks_uri.append(track_data['uri']) return top_10tracks_uri #Defining users and authorization codes username = '******' username_j = 'joselusko' scope = 'user-library-read user-top-read playlist-modify-public user-follow-read playlist-read-private playlist-modify-private' token = util.prompt_for_user_token(username, scope) token_j = util.prompt_for_user_token(username_j, scope) sp = spotipy.Spotify(auth=token) sp_j = spotipy.Spotify(auth=token_j) #I already created a playlist so to avoid to create a new one all the time I will rewrite on this one playlist_id = '3Uvw17LxK0xgJUiiGEebZE' playlist_url = 'https://open.spotify.com/playlist/3Uvw17LxK0xgJUiiGEebZE' #Finding my top artists 100 and their top 10 songs: print("Wait a minute, I'm looking into Cincin's top artists..")
import datetime #from spotify_auth import authenication_token, read_username_from_csv from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail load_dotenv() client_id_saved = os.environ.get("SPOTIFY_CLIENT_ID") client_secret_saved = os.environ.get("SPOTIFY_CLIENT_SECRET") redirect_uri_saved = os.environ.get("SPOTIPY_REDIRECT_URI") username = os.getenv("username") scope = 'user-library-read playlist-modify-public' # util.prompt_for_user_token(username, scope, client_id=client_id_saved, client_secret=client_secret_saved, redirect_uri=redirect_uri_saved) token = util.prompt_for_user_token(username, scope) def user_playlist_add_episodes(sp, user, playlist_id, episodes, position=None): """ Adds episodes to a playlist Parameters: - user - the id of the user - playlist_id - the id of the playlist - episodes - a list of track URIs, URLs or IDs - position - the position to add the tracks """ plid = sp._get_id("playlist", playlist_id)
import requests import sys import spotipy import spotipy.util as util #from config.config import USERNAME, SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRETSPOTIPY_REDIRECT_URI from bs4 import BeautifulSoup #for acessing private playlists scope= 'playlist-read-private' username = '******'; token = util.prompt_for_user_token( username, scope, client_id='3cb41450f466404399f3e0de3e4c89f2', client_secret= '51406619960a46c3a0fc8682e5152784', redirect_uri="http://localhost/" ) #function for prinitng song name and lyrics def show_lyrics(tracks): for i, item in enumerate(tracks['items']): track = item['track'] print(" %d %32.32s %s" % (i, track['artists'][0]['name'], track['name'])) artist = track['artists'][0]['name'] name = track['name'] #formatting song url for song_url = '{}-{}-lyrics'.format(str(artist).strip().replace(' ', '-').replace('(','').replace(')',''), str(name).strip().replace(' ', '-').replace('(','').replace(')','')) print (song_url) request = requests.get("https://genius.com/{}".format(song_url))
SPOTIPY_CLIENT_SECRET = "3168b907abf54925b8e482797f0eb718" REDIRECT_URI = "http://localhost:8888/" userScope = { "account": "user-read-private", "top": "user-top-read", "email": "user-read-email" } client_credentials_manager = SpotifyClientCredentials( client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET) sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) sp.trace = False token = util.prompt_for_user_token(USERNAME, scope=userScope['account'], client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET, redirect_uri=REDIRECT_URI) top_tracks = [] if token: sp = spotipy.Spotify(auth=token) results = sp.current_user_saved_tracks(limit=50) for item in results['items']: track = item['track'] #import pdb;pdb.set_trace() track_image_url = track['album']['images'][0]['url'] artist_name = track['artists'][0]['name'] track_name = track['name'] album_name = track['album']['name']
import os import spotipy.util as util import requests from lfuncs import lmap, lfilter client_id = os.environ['SPOTIPY_CLIENT_ID'] client_secret = os.environ['SPOTIPY_CLIENT_SECRET'] redirect_uri = 'http://localhost:8080/callback' token = util.prompt_for_user_token( 'lerner98', 'user-read-recently-played user-library-read', client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) base_url = 'https://api.spotify.com/v1/' rex_url = base_url + 'recommendations' trax_url = base_url + 'tracks' def return_token(): return token def format_track(track): return { 'artist': '"' + track['artists'][0]['name'] + '"', 'id': track['id'], 'name': '"' + track['name'] + '"'
import spotipy.util as util import gspread from oauth2client.service_account import ServiceAccountCredentials import spotipy from json.decoder import JSONDecodeError import json # get username from terminal username = "******" #12171678313 #Erase cache and prompt for user permission try: token = util.prompt_for_user_token(username) except: #os.remove(".cache-{}".format(username)) token = token = util.prompt_for_user_token( username, client_id='f572cf52d72b4e44ac55d6c14ba6f74a', client_secret='18f76a14e1554ad69b2d51070a9a67eb', redirect_uri='https://google.com/') #create spotify object spotifyObject = spotipy.Spotify(auth=token) #connect google sheets and add the spotify data to it scope = [ "https://spreadsheets.google.com/feeds",
add = Blueprint('add', __name__) import spotipy import spotipy.util as util from spotipy.oauth2 import SpotifyClientCredentials import csv #import pandas as pd from pprint import pprint client_id = '470a2b0a8f0f4313bd619a4e87a9db20' client_secret = '52d5aeb2f9e5418fbc9e13ab82c506aa' redirect_uri = 'http://localhost:8888/callback' scope = 'user-library-read' token = util.prompt_for_user_token(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) #takes an artists name #this triggers the rest of the program. #take the first public album available and pull those songs '''This function is for users that do have a Spotify account.''' def get_playlist_tracks(username, playlist_id): sp = spotipy.Spotify(auth=token) results = sp.user_playlist_tracks(username, playlist_id) tracks_user = results['items'] while (results['next']): results = sp.next(results) tracks_user.extend(results['items'])
import pprint import sys import spotipy import spotipy.util as util username="******" scope = 'playlist-modify-public' token = util.prompt_for_user_token(username, scope, client_id='72eca0e228434844a1638a6cc48e0ff5', client_secret='45c2a761720d4f1297510ef41f1c2b62', redirect_uri='http://localhost/') def create_playlist(username, playlist_name): sp = spotipy.Spotify(auth=token) sp.trace = False results = sp.user_playlist_create(username, playlist_name, public=True) playlist_id = results['id'] return playlist_id
def chunk_track_list(trackList): '''Split list of tracks into 100 track chunks. Spotify only allows 100 tracks to be added to a playlist at a time. ''' for i in range(0, len(trackList), 100): yield trackList[i:i + 100] parser = argparse.ArgumentParser(description='Find matching tracks between two Spotify user accounts.') parser.add_argument('username1', type=str, help='Username of first account for track matching. The BopMatch playlist is created in username1\'s library. Authentication for the account will be required.') parser.add_argument('username2', type=str, help='Username of second account for track matching. Only used for track matching, no authentication required.') parser.add_argument('matchType', type=int, help='0 = Match by Track, 1 = Match by Album, 2 = Match by Artist') args = parser.parse_args() #Obtain permission to create and modify playlists for username1 token = util.prompt_for_user_token(args.username1, scope='playlist-modify-public', client_id='409994c70c5d4e719eb2c4104755edb5', client_secret='1260f9d85a9f44bc9747f788d4c00a16', redirect_uri='http://localhost/callback') if token: sp = spotipy.Spotify(auth=token) #Download user playlist data and extract all tracks user1Tracks = get_playlist_tracks(args.username1) user2Tracks = get_playlist_tracks(args.username2) #Find matching tracks by artist, album, or track matchingTrackIDs = [] matchingTrackIDs.extend(match_tracks(user1Tracks, user2Tracks, args.matchType)) matchingTrackIDs.extend(match_tracks(user2Tracks, user1Tracks, args.matchType)) #Remove any duplicate track IDs matchingTrackIDs = list(set(matchingTrackIDs))
import spotipy import spotipy.util as util import os import sys scope = 'user-read-recently-played user-top-read user-library-modify user-library-read playlist-read-private playlist-modify-public playlist-modify-private playlist-read-collaborative' token1 = util.prompt_for_user_token( sys.argv[1], scope, client_id='7d2739378e2a47d8bc6cc89c63c5c4b0', client_secret='5d2535acb98847c5b166fadaee4fe436', redirect_uri='http://localhost:8888/callback/') print(token1)
def getToken(username, client_id, client_secret, redirect): try: token = util.prompt_for_user_token(username, 'playlist-modify-public', client_id, client_secret , redirect) except: #os.remove(f".cache-{username}") token = util.prompt_for_user_token(username, 'playlist-modify-public', client_id, client_secret, redirect) return token