Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _get_session(authenticate: bool = True) -> spotipy.Spotify:
if not os.getenv('SPOTIPY_CLIENT_ID'):
raise SystemExit(
"Spotify application credentials are missing. Rename .env.example to .env and"
" fill in the values"
)
if authenticate:
token = utils.login_user()
else:
token = utils.cached_token(scope=SCOPE)
if token:
return spotipy.Spotify(auth=token)
else:
if authenticate:
raise utils.DiversifyError(f"Unable to log in to your account")
else:
raise utils.DiversifyError("You are not logged in. Run [diversify login USERNAME] to log in.")
if not re.search(KeepWords, m.group(), re.I):
result = re.sub(re.escape(m.group()), '', result)
result = re.sub(StringRegex, '', result).strip()
result = ' '.join(result.split())
new_list = list(filter(None, re.split(split, result)))
first = new_list[0]
sep = 'aka'
sep2 = 'AKA'
new_list[0] = first.split(sep, 1)[0]
new_list[0] = first.split(sep2, 1)[0]
spotify_token = util.prompt_for_user_token(Config.username, Config.scope)
if spotify_token:
spot = spotipy.Spotify(auth=spotify_token)
artist = new_list[0]
track = new_list[1]
results = spot.search(q="artist:{} track:{}".format(artist, track, limit=1))
if results:
spottracks = results['tracks']['items']
if spottracks:
spotartist = spottracks[0]['artists'][0]['name']
spottitle = spottracks[0]['name']
spoturl = spottracks[0]['external_urls']['spotify']
update.effective_message.reply_text \
("► {0} - {1} \n{2}".format(spotartist, spottitle, spoturl))
else:
results = spot.search(q="artist:{} track:{}"
.format(track, artist, limit=1))
# shows related artists for the given seed artist
import spotipy
import sys
import pprint
if len(sys.argv) > 1:
artist_name = sys.argv[1]
else:
artist_name = 'weezer'
sp = spotipy.Spotify()
result = sp.search(q='artist:' + artist_name, type='artist')
try:
name = result['artists']['items'][0]['name']
uri = result['artists']['items'][0]['uri']
related = sp.artist_related_artists(uri)
print('Related artists for', name)
for artist in related['artists']:
print(' ', artist['name'])
except:
print("usage show_related.py [artist-name]")
def is_token_valid(token):
try:
spotify_client = spotipy.Spotify(auth=token)
spotify_client.current_user()
except spotipy.client.SpotifyException:
return False
return True
def load_more_tracks(core):
try:
token = auth.AuthHelper().get_token()
token = token['access_token']
spotify = spotipy.Spotify( auth = token )
response = spotify.recommendations(seed_artists = state['seed_artists'], seed_genres = state['seed_genres'], seed_tracks = state['seed_tracks'], limit = 5)
uris = []
for track in response['tracks']:
uris.append( track['uri'] )
core.tracklist.add( uris = uris )
except:
logger.error('RadioHandler: Failed to fetch recommendations from Spotify')
"Cannot read the playlist URI. See the help for expected format."
)
sys.stderr.write(
f"Searching for {playlist_username}'s playlist {playlistid}\n"
)
writer = csv.writer(sys.stdout, quoting=csv.QUOTE_ALL)
token = prompt_for_user_token(
username, scope=SPOTIFY_API_SCOPE,
client_id=client_id, client_secret=client_secret,
redirect_uri=redirect_uri
)
spotify = spotipy.Spotify(auth=token)
if playlist_username:
results = spotify.user_playlist(
playlist_username, playlistid, fields="name,tracks,next"
)
else:
results = spotify.playlist(
playlistid, fields="name,tracks,next"
)
sys.stdout.write(f"# Playlist: {results['name']}\n")
sys.stdout.write(f"# Description: from {open_spotify_uri}\n")
csv_write_header(writer)
tracks = results['tracks']
csv_write_tracks(writer, tracks)
def get_spotify_api(self):
try:
client_credentials_manager = SpotifyClientCredentials()
return spotipy.Spotify(client_credentials_manager=client_credentials_manager)
except Exception as e:
self.logger.error("Something went wrong getting Spotify API")
self.logger.error(e)
return None
import spotipy
sp = spotipy.Spotify()
results = sp.search(q='weezer', limit=20)
for i, t in enumerate(results['tracks']['items']):
print(' ', i, t['name'])
def GetSpotifyToken(self):
try:
if self.SpotifyUsername != "" and self.Spotifypassword != "" and self.SpotifyExpiryTime - time.time() < 60:
data = spotify_token.start_session(self.SpotifyUsername, self.Spotifypassword)
self.SpotifyAccessToken = data[0]
self.SpotifyExpiryTime = data[1]
self.SpotifyClient = spotipy.Spotify(auth=self.SpotifyAccessToken)
self.SpotifyUserId = self.SpotifyClient.current_user()["id"]
except requests.exceptions.ConnectionError:
pass
except Exception as e:
senderror(e)
def load_more_tracks( self ):
# this is crude, but it means we don't need to handle expired tokens
# TODO: address this when it's clear what Jodal and the team want to do with Pyspotify
self.refresh_spotify_token()
try:
token = self.spotify_token
token = token['access_token']
except:
logger.error('SpotmopFrontend: access_token missing or invalid')
try:
spotify = Spotify( auth = token )
response = spotify.recommendations(seed_artists = self.radio['seed_artists'], seed_genres = self.radio['seed_genres'], seed_tracks = self.radio['seed_tracks'], limit = 5)
uris = []
for track in response['tracks']:
uris.append( track['uri'] )
self.core.tracklist.add( uris = uris )
except:
logger.error('SpotmopFrontend: Failed to fetch recommendations from Spotify')