def setUpClass(self): if sys.version_info >= (3, 2): # >= Python3.2 only warnings.filterwarnings( "ignore", category=ResourceWarning, # noqa message="unclosed.*<ssl.SSLSocket.*>") missing = list(filter(lambda var: not os.getenv(CCEV[var]), CCEV)) if missing: raise Exception( ('Please set the client credentials for the test application' ' using the following environment variables: {}').format( CCEV.values())) self.username = os.getenv(CCEV['client_username']) self.scope = ( 'playlist-modify-public ' 'user-library-read ' 'user-follow-read ' 'user-library-modify ' 'user-read-private ' 'user-top-read ' 'user-follow-modify ' 'user-read-recently-played ' 'ugc-image-upload' ) self.token = prompt_for_user_token(self.username, scope=self.scope) self.spotify = Spotify(auth=self.token)
def setUpClass(cls): cls.four_tracks = ["spotify:track:6RtPijgfPKROxEzTHNRiDp", "spotify:track:7IHOIqZUUInxjVkko181PB", "4VrWlk8IQxevMvERoX08iC", "http://open.spotify.com/track/3cySlItpiPiIAzU3NyHCJf"] cls.album_ids = ["spotify:album:6kL09DaURb7rAoqqaA51KU", "spotify:album:6RTzC0rDbvagTSJLlY7AKl"] cls.username = os.getenv(CCEV['client_username']) scope = ( 'playlist-modify-public ' 'user-library-read ' 'user-follow-read ' 'user-library-modify ' 'user-read-private ' 'user-top-read ' 'user-follow-modify ' 'user-read-recently-played ' 'ugc-image-upload ' 'user-read-playback-state' ) token = prompt_for_user_token(cls.username, scope=scope) cls.spotify = Spotify(auth=token)
def setUpClass(cls): cls.four_tracks = ["spotify:track:6RtPijgfPKROxEzTHNRiDp", "spotify:track:7IHOIqZUUInxjVkko181PB", "4VrWlk8IQxevMvERoX08iC", "http://open.spotify.com/track/3cySlItpiPiIAzU3NyHCJf"] cls.other_tracks = ["spotify:track:2wySlB6vMzCbQrRnNGOYKa", "spotify:track:29xKs5BAHlmlX1u4gzQAbJ", "spotify:track:1PB7gRWcvefzu7t3LJLUlf"] cls.username = os.getenv(CCEV['client_username']) scope = ( 'playlist-modify-public ' 'user-library-read ' 'user-follow-read ' 'user-library-modify ' 'user-read-private ' 'user-top-read ' 'user-follow-modify ' 'user-read-recently-played ' 'ugc-image-upload ' 'user-read-playback-state' ) token = prompt_for_user_token(cls.username, scope=scope) cls.spotify = Spotify(auth=token) cls.new_playlist_name = 'spotipy-playlist-test' cls.new_playlist = helpers.get_spotify_playlist( cls.spotify, cls.new_playlist_name, cls.username) or \ helpers.create_spotify_playlist( cls.spotify, cls.new_playlist_name, cls.username) cls.new_playlist_uri = cls.new_playlist['uri']
def setUpClass(self): missing = list(filter(lambda var: not os.getenv(CCEV[var]), CCEV)) if missing: raise Exception( ('Please set the client credentials for the test application' ' using the following environment variables: {}').format( CCEV.values())) self.username = os.getenv(CCEV['client_username']) self.scope = ( 'playlist-modify-public ' 'user-library-read ' 'user-follow-read ' 'user-library-modify ' 'user-read-private ' 'user-top-read ' 'user-follow-modify' ) self.token = prompt_for_user_token(self.username, scope=self.scope) self.spotify = Spotify(auth=self.token)
def authorize(self, username=config.username, client_id=config.client_id, client_secret=config.client_secret): self.token = spotipy.prompt_for_user_token(username=username, scope=self.scope, client_id=client_id, client_secret=client_secret, redirect_uri=self.uri)
def prev_song(self): token = spotipy.prompt_for_user_token("chesterwoo409", scope=scope, client_id=client_id, client_secret=secret_id, redirect_uri=redirect_uri) if token: sp = spotipy.Spotify(auth=token) sp.previous_track() self.update_song()
def setUpClass(self): missing = list(filter(lambda var: not os.getenv(CCEV[var]), CCEV)) if missing: raise Exception(('Please set the client credentials for the test ' 'the following environment variables: {}').format( CCEV.values())) self.username = os.getenv(CCEV['client_username']) self.scope = 'user-library-read' self.token = prompt_for_user_token(self.username, scope=self.scope) self.spotify = Spotify( client_credentials_manager=SpotifyClientCredentials())
def login(self, username, client_id, client_secret, redirect_uri): token = prompt_for_user_token( username=username, scope=SCOPE, client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, ) client_credentials_manager = SpotifyClientCredentials( client_id=client_id, client_secret=client_secret) spotify = Spotify( auth=token, client_credentials_manager=client_credentials_manager) spotify.trace = False self.spotify = spotify
def setUpClass(self): missing = filter(lambda var: not os.getenv(CCEV[var]), CCEV) if missing: raise Exception( 'Please set the client credentials for the test application using the following environment variables: {}' .format(CCEV.values())) self.username = os.getenv(CCEV['client_username']) self.scope = 'user-library-read' self.token = prompt_for_user_token(self.username, scope=self.scope) self.spotify = Spotify(auth=self.token)
def return_auth_client(cls, user_name): """ This method opens a prompt for user to connect to spotify. If authorized by the user, they'll be redirected to a predefined redirected URI with an authentication token attached to it. :rtype str: the striped authentication token. """ cls.username = user_name token = prompt_for_user_token(client_id=Spotify.CLIENT_ID, client_secret=Spotify.CLIENT_SECRET, redirect_uri=cls.LOCAL_SERVER, scope=Spotify.SPOTIFY_ACCESS_SCOPE, username=cls.username) cls.spotify = SpotifyApiClient(auth=token) return cls.spotify
def setUpClass(cls): cls.username = os.getenv(CCEV['client_username']) scope = ('playlist-modify-public ' 'user-library-read ' 'user-follow-read ' 'user-library-modify ' 'user-read-private ' 'user-top-read ' 'user-follow-modify ' 'user-read-recently-played ' 'ugc-image-upload ' 'user-read-playback-state') token = prompt_for_user_token(cls.username, scope=scope) cls.spotify = Spotify(auth=token)
def setUpClass(cls): cls.four_tracks = [ "spotify:track:6RtPijgfPKROxEzTHNRiDp", "spotify:track:7IHOIqZUUInxjVkko181PB", "4VrWlk8IQxevMvERoX08iC", "http://open.spotify.com/track/3cySlItpiPiIAzU3NyHCJf" ] cls.other_tracks = [ "spotify:track:2wySlB6vMzCbQrRnNGOYKa", "spotify:track:29xKs5BAHlmlX1u4gzQAbJ", "spotify:track:1PB7gRWcvefzu7t3LJLUlf" ] cls.username = os.getenv(CCEV['client_username']) # be wary here, episodes sometimes go away forever # which could cause tests that rely on four_episodes # to fail cls.four_episodes = [ "spotify:episode:7f9e73vfXKRqR6uCggK2Xy", "spotify:episode:4wA1RLFNOWCJ8iprngXmM0", "spotify:episode:32vhLjJjT7m3f9DFCJUCVZ", "spotify:episode:7cRcsGYYRUFo1OF3RgRzdx", ] scope = ('playlist-modify-public ' 'user-library-read ' 'user-follow-read ' 'user-library-modify ' 'user-read-private ' 'user-top-read ' 'user-follow-modify ' 'user-read-recently-played ' 'ugc-image-upload ' 'user-read-playback-state') token = prompt_for_user_token(cls.username, scope=scope) cls.spotify = Spotify(auth=token) cls.new_playlist_name = 'spotipy-playlist-test' cls.new_playlist = helpers.get_spotify_playlist( cls.spotify, cls.new_playlist_name, cls.username) or \ helpers.create_spotify_playlist( cls.spotify, cls.new_playlist_name, cls.username) cls.new_playlist_uri = cls.new_playlist['uri']
def volume(command): token = spotipy.prompt_for_user_token("chesterwoo409", scope=scope, client_id=client_id, client_secret=secret_id, redirect_uri=redirect_uri) if token: sp = spotipy.Spotify(auth=token) for d in sp.devices()['devices']: if d['is_active']: current_volume = d['volume_percent'] if command == 'up': if current_volume >= 95: sp.volume(100) else: sp.volume(current_volume + 5) elif command == 'down': if current_volume <= 5: sp.volume(0) else: sp.volume(current_volume - 5)
def play_pause(self): token = spotipy.prompt_for_user_token("chesterwoo409", scope=scope, client_id=client_id, client_secret=secret_id, redirect_uri=redirect_uri) if token: sp = spotipy.Spotify(auth=token) cp = sp.currently_playing() global g_playing if cp is not None and cp['is_playing'] is True: sp.pause_playback() self.is_pause = True g_playing = False else: active = False device_list = sp.devices()['devices'] for d in device_list: if d['is_active'] is True: active = True device = None if not active: for d in device_list: if d["name"] == "Chester's Echo Dot": d['is_active'] = True device = alexa_id # self.curr_volume = d['volume_percent'] self.is_pause = False try: sp.transfer_playback(device_id=device, force_play=True) sp.shuffle(True) g_playing = True self.update_song() except Exception as e: self.play_pause()
def setUpClass(cls): username = os.getenv(CCEV['client_username']) token = prompt_for_user_token(username) cls.spotify = Spotify(auth=token)
load_dotenv() date = input('Enter date to scratch YYYY-MM-DD: ') song_names = get_name_songs(date) spotipy_sesion = spotipy.Spotify( auth_manager=SpotifyOAuth( scope="playlist-modify-private", redirect_uri='http://localhost', show_dialog=True, cache_path="token.txt" ) ) user_id = spotipy_sesion.me()['id'] spotipy.prompt_for_user_token( user_id, scope='playlist-modify-public', redirect_uri='http://localhost' ) def get_user_token(): return spotipy_sesion.current_user() def get_spotify_id_songs(): spotipy_songs = [] for song in song_names: try: print(f'Searching: {song}') ns = spotipy_sesion.search(song, limit=1) spotipy_songs.append(ns['tracks']['items'][0]['uri']) except Exception as e:
import webbrowser import spotipy as util from json.decoder import JSONDecodeError from spotipy.oauth2 import SpotifyClientCredentials from spotipy.oauth2 import SpotifyOAuth import numpy as np # setup #jbjiwxnlxxr53e7awx4vu4y83 global username username = sys.argv[0] scope = 'user-read-private user-read-playback-state user-modify-playback-state playlist-read-collaborative playlist-modify-public playlist-read-private playlist-modify-private' #erase cashe prompt for user permission try: token = util.prompt_for_user_token(username, scope) except: os.remove(f".cashe-{username}") token = util.prompt_for_user_token(username, scope) #create our spotifyObject spotifyObject = spotipy.Spotify(auth=token) devices = spotifyObject.devices() deviceID = devices['devices'][0]['id'] # entry page, currently playing # search artist and display most recent single name, album cover, genre, followers def options():
def update_song(self): # Handles updating songs if changed token = spotipy.prompt_for_user_token("chesterwoo409", scope=scope, client_id=client_id, client_secret=secret_id, redirect_uri=redirect_uri) if token: sp = spotipy.Spotify(auth=token) cp = sp.currently_playing() global g_playing if cp is not None: currently_playing2 = cp['item']['name'] current_artist = cp['item']['album']['artists'][0]['name'] if cp['is_playing']: g_playing = True self.is_pause = False self.idle = 0 self.hidden = False for i in range(len(currently_playing2)): currently_playing2 = currently_playing2[:i * 2 + 1] + ' ' + currently_playing2[ i * 2 + 1:] for i in range(len(current_artist)): current_artist = current_artist[:i * 2 + 1] + ' ' + current_artist[ i * 2 + 1:] self.current_artist = current_artist if self.currently_playing != currently_playing2: self.currently_playing = currently_playing2 self.song_canvas.itemconfig( self.cnv_currently_playing, text=self.currently_playing) self.song_canvas.itemconfig(self.cnv_current_artist, text=self.current_artist) self.song_length = (cp['item']['duration_ms'] - cp['progress_ms']) + ( 4 - (cp['item']['duration_ms'] - cp['progress_ms']) % 4) if len(self.currently_playing) > 56: self.song_canvas.coords( "marquee_song", int(self.song_canvas['width']) // 2, 50) else: self.song_canvas.coords( "marquee_song", int(self.song_canvas['width']) // 1.9, 50) self.song_canvas.coords( "marquee_artist", int(self.song_canvas['width']) // 1.9, 100) else: self.is_pause = True g_playing = False self.song_length = ( cp['item']['duration_ms'] - cp['progress_ms'] ) + (4 - (cp['item']['duration_ms'] - cp['progress_ms']) % 4) else: self.song_length = 10000
def main(): print( "Getting this week's latest in music, as reviewed by theneedledrop!\n" "------------------------------------------------------------------") # spotify credentials spotify_client_id = tm_spotify_id spotify_client_secret = tm_spotify_secret spotify_user_id = spot_user_id spotify_username = spot_username spotify_redirect_uri = spot_redirect_uri '''Authorize Spotify user account ''' spotify_token = spotipy.prompt_for_user_token( spotify_username, 'user-read-private,playlist-read-private,playlist-modify-private,playlist-modify,playlist-modify-public', client_id=spotify_client_id, client_secret=spotify_client_secret, redirect_uri=spotify_redirect_uri) # youtube credentials api_service_name = "youtube" api_version = "v3" client_secrets_file = tm_web_secret ''' Authorize Youtube account once and store credentials with pickle ''' creds = None if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # if there are no valid credentials, provide the user with log in popup if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file( client_secrets_file, scopes) creds = flow.run_console() # save the credentials for subsequent runs with open('token.pickle', 'wb') as token: pickle.dump(creds, token) # create a youtube client youtube = googleapiclient.discovery.build(api_service_name, api_version, credentials=creds) ''' Get the most recent weekly track roundup video ''' # collect recent weekly track roundup videos request = youtube.playlistItems().list( part="snippet", playlistId="PLP4CSgl7K7or84AAhr7zlLNpghEnKWu2c", maxResults=2) response = request.execute() # find the most recent video and get its details recent_roundup_obj = "" for (k, v) in response.items(): if k == "items": recent_roundup_obj = v[0] break # get the title, description, and parsed date from the most recent video title = "" description = "" for (k, v) in recent_roundup_obj.items(): if k == "snippet": snip_obj = json.loads(json.dumps(v)) description = json.loads(json.dumps(snip_obj['description'])) title = json.loads(json.dumps(snip_obj['title'])) break date = title[22:26] + '/' + str(datetime.datetime.now().year) ''' Get last week's old Spotify playlists and unfollow them ''' # This is to make sure our list of playlists doesn't get cluttered. By now, i should've listened to last week's # songs already. query = "https://api.spotify.com/v1/users/{}/playlists".format( spotify_user_id) request = requests.get(query, headers={ "Content-Type": "application/json", "Authorization": "Bearer {}".format(spotify_token) }) response = request.json() items = response["items"] playlist_names = [ "Best tracks of the week", "Meh tracks of the week", "Worst tracks of the week" ] playlists_ids_to_unfollow = [] for item in items: playlist_name = item["name"] playlist_date = playlist_name[playlist_name.find(":") + 2:] playlist_name = playlist_name[:playlist_name.find(":")] if playlist_name in playlist_names and playlist_date != date: playlists_ids_to_unfollow.append(item["id"]) count = 0 length = len(playlists_ids_to_unfollow) for playlist_id in range(length): query = "https://api.spotify.com/v1/playlists/{}/followers".format( playlists_ids_to_unfollow[count]) requests.delete(query, headers={ "Content-Type": "application/json", "Authorization": "Bearer {}".format(spotify_token) }) count += 1 ''' Get last week's old Youtube playlists and unfollow them ''' request = youtube.playlists().list(part="snippet,contentDetails", maxResults=15, mine=True) response = request.execute() items = response["items"] playlist_names = [ "Best tracks of the week", "Meh tracks of the week", "Worst tracks of the week" ] playlists_ids_to_unfollow = [] for item in items: playlist_name = item["snippet"]["title"] playlist_date = playlist_name[playlist_name.find(":") + 2:] playlist_name = playlist_name[:playlist_name.find(":")] if playlist_name in playlist_names and playlist_date != date: playlists_ids_to_unfollow.append(item["id"]) count = 0 length = len(playlists_ids_to_unfollow) for playlist_id in range(length): request = youtube.playlists().delete( id=playlists_ids_to_unfollow[count]) request.execute() count += 1 ''' Create a "best"/"meh"/"worst" tracks of the week playlist on Youtube ''' best_playlist_id = create_best_playlist(youtube, date) meh_playlist_id = create_meh_playlist(youtube, date) worst_playlist_id = create_worst_playlist(youtube, date) ''' Create a "best"/"meh"/"worst" tracks of the week playlist on Spotify ''' playlist_ids = create_spotify_playlists(spotify_user_id, spotify_token, date) id_enum = 0 # best: 1, meh: 2, worst: 3 for line in description.splitlines(): if "best tracks" in line.lower(): id_enum = 1 continue elif "meh" in line.lower(): id_enum = 2 continue elif "worst tracks" in line.lower(): id_enum = 3 continue try: extracted_id = str(get_yt_video_id(line)).strip(' ') if extracted_id is not None and 1 <= id_enum <= 3: # found a video and it's in a best/meh/worst section # search up the video for its key attributes request = youtube.videos().list( part="snippet,contentDetails,statistics", id=extracted_id) request.execute() if id_enum == 1: add_to_youtube_playlist(youtube, best_playlist_id, extracted_id) elif id_enum == 2: add_to_youtube_playlist(youtube, meh_playlist_id, extracted_id) elif id_enum == 3: add_to_youtube_playlist(youtube, worst_playlist_id, extracted_id) except ValueError: if " - " in line.lower(): og_song_name = line[line.find("-") + 2:] if "(" in line.lower(): line = line[:line.find("(") - 1] if "ft" in line.lower(): line = line[:line.find("ft") - 1] if "*" in line.lower(): line = line[:line.find("*") - 1] artist = line[:line.find("-") - 1] song_name = line[line.find("-") + 2:] if "&" in song_name: song_name = ''.join(c if c != '&' else 'and' for c in song_name) song_uri = get_spotify_uri(spotify_token, song_name, artist, og_song_name) if id_enum == 1: add_song_to_spotify_playlist(playlist_ids[0], song_uri, spotify_token) elif id_enum == 2: add_song_to_spotify_playlist(playlist_ids[1], song_uri, spotify_token) elif id_enum == 3: add_song_to_spotify_playlist(playlist_ids[2], song_uri, spotify_token) continue print( "Playlists created!\nLog in to Spotify to view your playlists!\nAlso, visit " "https://www.youtube.com/feed/library to view your playlists on Youtube." )
# shows artist info for a URN or URL import spotipy token = spotipy.prompt_for_user_token('SpoQ') sp = spotipy.Spotify(auth=token) result = sp.search('radiohead') print(result) response = sp.categories() for cat in response['categories']['items']: cat_id = cat['id'] response = sp.category_playlists(category_id=cat_id) print(response['playlists'])