def authenticate(): class RequestHandler(BaseHTTPRequestHandler): callbackUri = None def do_GET(self): self.send_response(200, "OK") self.end_headers() self.wfile.write( pkg_resources.resource_string(__name__, "html/success.html")) RequestHandler.callbackUri = self.path config = get_config() oauth = SpotifyOAuth( client_id=config["client_id"], client_secret=config["client_secret"], redirect_uri="http://localhost:8000", scope=scope, cache_path=dirs.user_cache_dir, ) token_info = oauth.get_cached_token() if not token_info: url = oauth.get_authorize_url() webbrowser.open(url) server = HTTPServer(('', 8000), RequestHandler) server.handle_request() code = oauth.parse_response_code(RequestHandler.callbackUri) oauth.get_access_token(code, as_dict=False) return oauth
def get_track_and_artists_name_from_api(): """ you should set three environment variables: SPOTIPY_CLIENT_ID SPOTIPY_CLIENT_SECRET SPOTIPY_REDIRECT_URI you need to set this value in your development dashboard this can be set this to http://127.0.0.1 and in the first time execute you have to authenticate you can get these from Spotify development dashboard """ auth_manager = SpotifyOAuth(scope='user-read-currently-playing') token = auth_manager.get_access_token(as_dict=False) sp = spotipy.Spotify(auth=token) current_track = sp.current_user_playing_track() if current_track: artists = [] for i in current_track['item']['artists']: artists.append(i['name']) # append name of artist to artists list playing_track_name = current_track['item']['name'] artists = ','.join(artists) return artists, playing_track_name return False, False
def login() -> Spotify: """ Attempt to log in to Spotify as the current user These OS Env variables must be set: SPOTIPY_CLIENT_ID SPOTIPY_CLIENT_SECRET SPOTIPY_REDIRECT_URI :return: Spotify session """ scope = 'user-library-read ' \ 'playlist-read-private ' \ 'playlist-modify-private ' \ 'playlist-modify-public ' \ 'user-library-modify ' \ 'user-read-recently-played' auth = SpotifyOAuth(scope=scope, username=USERNAME, cache_path=os.path.join(CACHE_DIR, 'auth_token.json')) token_info = auth.get_cached_token() if token_info: logging.info('Using cached token for login') return _get_login_session(token_info['access_token']) code = auth.parse_response_code(RESPONSE_URL) if code: logging.info('Found response URL. Getting an access token...') token_info = auth.get_access_token(code) return _get_login_session(token_info['access_token']) logging.warning( 'Access token not found. Please use the below URL to authorize this ' 'application and then set the RESPONSE_URL env variable to the URL ' 'spotify responds with and run this application again') logging.warning(auth.get_authorize_url()) sys.exit(0)