def randomShuffle(self, token, playlistId, shuffleTime): # get user spotifyObject = Spotify(auth=token) spotifyUser = spotifyObject.current_user() username = spotifyUser['id'] tracks = [] songsAdded = 0 numSongsToAdd = int(int(shuffleTime) / 2) playlist = spotifyObject.user_playlist_tracks(user=username, playlist_id=playlistId) numberOfSongs = int(playlist['total']) if numberOfSongs < numSongsToAdd: numSongsToAdd = numberOfSongs while songsAdded < numSongsToAdd: for i in range (0, 5): offsetNum = random.randint(0, numberOfSongs-1) playlist = spotifyObject.user_playlist_tracks(user=username, playlist_id=playlistId, offset=offsetNum) song = random.choice(playlist['items']) if song['track']['id'] not in tracks: spotifyObject.add_to_queue(song['track']['id']) tracks.append(song['track']['id']) songsAdded = songsAdded + 1
def download_name(self, artist, song, output=stock_output, quality=stock_quality, recursive_quality=stock_recursive_quality, recursive_download=stock_recursive_download, not_interface=stock_not_interface): query = "track:{} artist:{}".format(song, artist) try: search = self.spo.search(query) except: self.spo = Spotify(generate_token()) search = self.spo.search(query) try: return self.download_trackspo( search['tracks']['items'][0]['external_urls']['spotify'], output, quality, recursive_quality, recursive_download, not_interface) except IndexError: raise exceptions.TrackNotFound("Track not found: :(")
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Spotify from a config entry.""" implementation = await async_get_config_entry_implementation(hass, entry) session = OAuth2Session(hass, entry, implementation) try: await session.async_ensure_token_valid() except aiohttp.ClientError as err: raise ConfigEntryNotReady from err spotify = Spotify(auth=session.token["access_token"]) try: current_user = await hass.async_add_executor_job(spotify.me) except SpotifyException as err: raise ConfigEntryNotReady from err hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = { DATA_SPOTIFY_CLIENT: spotify, DATA_SPOTIFY_ME: current_user, DATA_SPOTIFY_SESSION: session, } if not set(session.token["scope"].split(" ")).issuperset(SPOTIFY_SCOPES): hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_REAUTH}, data=entry.data, )) hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, MEDIA_PLAYER_DOMAIN)) return True
def main(): client_credentials_manager = SpotifyClientCredentials( client_id=CLIENT_ID, client_secret=CLIENT_SERCRET, ) api = Spotify(client_credentials_manager=client_credentials_manager) names = {} nodes = get_successors(api, ROOT_NODE, ROOT_DEPTH, names) del names[ROOT_NODE] nodes.discard(ROOT_NODE) save_successors(ROOT_NODE, nodes, names) for node in nodes: print(node, names[node]) successors = get_successors(api, node) save_successors(node, successors)
async def async_oauth_create_entry(self, data: dict[str, Any]) -> FlowResult: """Create an entry for Spotify.""" spotify = Spotify(auth=data["token"]["access_token"]) try: current_user = await self.hass.async_add_executor_job( spotify.current_user) except Exception: # pylint: disable=broad-except return self.async_abort(reason="connection_error") name = data["id"] = current_user["id"] if self.reauth_entry and self.reauth_entry.data["id"] != current_user[ "id"]: return self.async_abort(reason="reauth_account_mismatch") if current_user.get("display_name"): name = current_user["display_name"] data["name"] = name await self.async_set_unique_id(current_user["id"]) return self.async_create_entry(title=name, data=data)
def akttym(): SCOPE = 'user-library-modify,user-read-playback-state' dir_path = os.path.dirname(os.path.realpath(__file__)) config = yaml.safe_load(open(dir_path + '/config.yaml')) check_config(config, dir_path) token = util.prompt_for_user_token(config['username'], SCOPE, client_id=config['client_id'], client_secret=config['client_secret'], redirect_uri='http://localhost:1911/', cache_path=dir_path + '/cache') if token: sp = Spotify(auth=token) track = sp.current_playback() if track is not None: sp.current_user_saved_tracks_add([track['item']['id']]) logging.warning("added %s to %s's library", track['item']['name'], config['username']) else: logging.warning("nothing is playing currently, aborting") else: logging.warning("Can't get token for %s", config['username'])
def download_trackspo( self, URL, output = stock_output + "/", quality = stock_quality, recursive_quality = stock_recursive_quality, recursive_download = stock_recursive_download, not_interface = stock_not_interface ): if "?" in URL: URL, a = URL.split("?") try: url = self.spo.track(URL) except Exception as a: if not "The access token expired" in str(a): raise exceptions.InvalidLink("Invalid link ;)") self.spo = Spotify( auth = generate_token() ) url = self.spo.track(URL) isrc = url['external_ids']['isrc'] url = request( "https://api.deezer.com/track/isrc:" + isrc, True ).json() name = self.download_trackdee( url['link'], output, quality, recursive_quality, recursive_download, not_interface ) return name
def spotify_engine(parsed_songs, spotify_clientid, spotify_secret, located_songs_path, spotify_results_limit, delay_spotify): previously_reported = load_json(located_songs_path) token = SpotifyClientCredentials( client_id=spotify_clientid, client_secret=spotify_secret).get_access_token() spotify_link = Spotify(auth=token) new_spotify_uris = [] print("Starting lookup with Spotify") for song in parsed_songs: song_details = spotify_lookup(spotify_link, song, spotify_results_limit) wait_time = (float(randint(5, 20)) / 10) * delay_spotify sys.stdout.write('.') sys.stdout.flush() sleep(wait_time) if song_details: if song_details["uri"] not in previously_reported: print("\nSearched for %s by %s (from %s)" % (song["track"], song["artist"], song["album"])) # artist:0, song:1, album:2 print("\nFound %s by %s (%s)" % (song_details["track_name"], song_details["artists"], song_details["album"])) new_spotify_uris.append(song_details["uri"]) print("\nFound %s new songs on Spotify" % len(new_spotify_uris)) for spotify_uri in new_spotify_uris: previously_reported.append(spotify_uri) save_json(located_songs_path, previously_reported) print("Paste these into a spotify playlist:") for song in new_spotify_uris: print(song)
def spotify_connect(session_id, code=''): ''' Connect to the Spotify API using the token associated with the given session ID, generating one if it does not already exist. ''' token = None cache_path = CACHE + session_id sp_oauth = SpotifyOAuth(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, scope=SCOPE, cache_path=cache_path) token_info = sp_oauth.get_cached_token() if token_info: token = token_info['access_token'] elif code: token_info = sp_oauth.get_access_token(code) token = token_info['access_token'] if token: return Spotify(token, requests_timeout=30, retries=1) else: return sp_oauth.get_authorize_url()
def setUpClass(cls): scope = ('user-follow-read ' 'user-follow-modify ') auth_manager = SpotifyImplicitGrant(scope=scope, cache_path=".cache-implicittest") cls.spotify = Spotify(auth_manager=auth_manager)
def test_force_no_requests_session(self): with_no_session = Spotify(auth=self.token, requests_session=False) self.assertFalse(isinstance(with_no_session._session, requests.Session)) self.assertTrue( with_no_session.user(user="******")["uri"] == "spotify:user:akx")
def download_albumspo(self, URL, output=stock_output + "/", quality=stock_quality, recursive_quality=stock_recursive_quality, recursive_download=stock_recursive_download, not_interface=stock_not_interface, zips=stock_zip): URL = URL.split("?")[0] try: tracks = self.spo.album(URL) except Exception as a: if not "The access token expired" in str(a): raise exceptions.InvalidLink("Invalid link ;)") self.spo = Spotify(generate_token()) tracks = self.spo.album(URL) tot = tracks['total_tracks'] try: upc = tracks['external_ids']['upc'] while upc[0] == "0": upc = upc[1:] url = request("https://api.deezer.com/album/upc:%s" % upc).json() names = self.download_albumdee(url['link'], output, quality, recursive_quality, recursive_download, not_interface, zips) except KeyError: search = tot // 5 try: url = self.spo.track(tracks['tracks']['items'][search] ['external_urls']['spotify']) except: self.spo = Spotify(generate_token()) url = self.spo.track(tracks['tracks']['items'][search] ['external_urls']['spotify']) isrc = url['external_ids']['isrc'] try: ids = request("https://api.deezer.com/track/isrc:%s" % isrc, True).json()['album']['id'] tracks = request("https://api.deezer.com/album/%d" % ids, True).json() if tot != tracks['nb_tracks']: raise exceptions.TrackNotFound("") names = self.download_albumdee(tracks['link'], output, quality, recursive_quality, recursive_download, not_interface, zips) except (exceptions.TrackNotFound, exceptions.NoDataApi): raise exceptions.AlbumNotFound("Album %s not found :(" % tracks['name']) return names
def setUpClass(self): self.spotify = Spotify( client_credentials_manager=SpotifyClientCredentials()) self.spotify.trace = False
def __init__(self): credentials = SpotifyClientCredentials( get_config("spotify", "CLIENT_ID"), get_config("spotify", "CLIENT_SECRET")) self.sp = Spotify(client_credentials_manager=credentials)
def Link(link, chat_id, quality, message_id): global spo global del1 del1 += 1 done = 0 quali = quality.split("MP3_")[-1] link = link.split("?")[0] ids = link.split("/")[-1] try: if "track/" in link: if "spotify" in link: try: url = spo.track(link) except Exception as a: if not "The access token expired" in str(a): sendMessage(chat_id, "Invalid link %s ;)" % link, reply_to_message_id=message_id) delete(chat_id) return spo = Spotify(generate_token()) url = spo.track(link) try: image1 = url['album']['images'][0]['url'] except IndexError: image1 = song_default_image name = url['name'] artist = url['album']['artists'][0]['name'] album = url['album']['name'] date = url['album']['release_date'] elif "deezer" in link: kind = "track" api_link = api_track % ids try: url = reque(api_link, chat_id, True).json() except AttributeError: delete(chat_id) return image1 = check_image(url['album']['cover_xl'], ids, kind) name = url['title'] artist = url['artist']['name'] album = url['album']['title'] date = url['album']['release_date'] if any(a in link for a in services_supported): sendPhoto(chat_id, image1, caption=(send_image_track_query % (name, artist, album, date))) track(link, chat_id, quality) else: sendMessage(chat_id, not_supported_links % link) elif "album/" in link: links = [] count = [0] if "spotify" in link: try: tracks = spo.album(link) except Exception as a: if not "The access token expired" in str(a): sendMessage(chat_id, "Invalid link %s ;)" % link, reply_to_message_id=message_id) delete(chat_id) return spo = Spotify(generate_token()) tracks = spo.album(link) try: image3 = tracks['images'][2]['url'] image1 = tracks['images'][0]['url'] except IndexError: image3 = image_resize(song_default_image, 90) image1 = song_default_image name = tracks['name'] artist = tracks['artists'][0]['name'] date = tracks['release_date'] tot = tracks['total_tracks'] def lazy(a): count[0] += a['duration_ms'] links.append(a['external_urls']['spotify']) for a in tracks['tracks']['items']: lazy(a) tracks = tracks['tracks'] for a in range(tot // 50 - 1): try: tracks = spo.next(tracks) except: spo = Spotify(generate_token()) tracks = spo.next(tracks) for a in tracks['items']: lazy(a) count[0] //= 1000 mode = downloa.download_albumspo elif "deezer" in link: api_link = api_album % ids kind = "album" try: url = reque(api_link, chat_id, True).json() except AttributeError: delete(chat_id) return count[0] = url['duration'] image1 = check_image(url['cover_xl'], ids, kind) image3 = image_resize(image1, 90) tot = url['nb_tracks'] links = [a['link'] for a in url['tracks']['data']] name = url['title'] artist = url['artist']['name'] date = url['release_date'] mode = downloa.download_albumdee if any(a in link for a in services_supported): if count[0] > seconds_limits_album: sendMessage( chat_id, "If you do this again I will come to your home and I will ddos your ass :)" ) delete(chat_id) return message_id = sendPhoto( chat_id, image1, caption=(send_image_album_query % (name, artist, date, tot)))['message_id'] conn = connect(db_file) c = conn.cursor() exists = [] for a in links: ids = a.split("/")[-1] lins = "track/%s" % ids exist = c.execute(where_query.format(lins, quali)).fetchone() if exist: exists.append(exist) if len(exists) < len(links) // 3: z = mode(link, quality=quality, recursive_quality=True, recursive_download=True, not_interface=not_interface) image3 = get_image(image3) for a in range(len(z)): sendAudio(chat_id, z[a], links[a], image3) else: for a in links: track(a, chat_id, quality) done = 1 else: sendMessage(chat_id, not_supported_links % link) elif "playlist/" in link: links = [] if "spotify" in link: musi = link.split("/") try: tracks = spo.user_playlist(musi[-3], musi[-1]) except Exception as a: if not "The access token expired" in str(a): sendMessage(chat_id, "Invalid link ;)", reply_to_message_id=message_id) delete(chat_id) return spo = Spotify(generate_token()) tracks = spo.user_playlist(musi[-3], musi[-1]) try: image1 = tracks['images'][0]['url'] except IndexError: image1 = song_default_image def lazy(a): try: links.append(a['track']['external_urls']['spotify']) except (KeyError, TypeError): links.append("Error :(") for a in tracks['tracks']['items']: lazy(a) added = tracks['tracks']['items'][0]['added_at'] owner = tracks['owner']['display_name'] tot = tracks['tracks']['total'] tracks = tracks['tracks'] for a in range(tot // 100 - 1): try: tracks = spo.next(tracks) except: spo = Spotify(generate_token()) tracks = spo.next(tracks) for a in tracks['items']: lazy(a) elif "deezer" in link: api_link = api_playlist % ids try: url = reque(api_link, chat_id, True).json() except AttributeError: delete(chat_id) return links = [a['link'] for a in url['tracks']['data']] image1 = url['picture_xl'] tot = url['nb_tracks'] added = url['creation_date'] owner = url['creator']['name'] if any(a in link for a in services_supported): if tot > max_songs: sendMessage(chat_id, "F**k you") delete(chat_id) return sendPhoto(chat_id, image1, caption=(send_image_playlist_query % (added, owner, tot))) for a in links: if a.startswith("http"): try: track(a, chat_id, quality) except: sendMessage(chat_id, "Cannot download %s:(" % a) else: sendMessage(chat_id, a) done = 1 else: sendMessage(chat_id, not_supported_links % link) elif "artist/" in link: if "deezer" in link: api_link = api_artist % ids try: url = reque(api_link, chat_id, True).json() except AttributeError: delete(chat_id) return keyboard = [[ InlineKeyboardButton( queries['top']['text'], callback_data=queries['top']['query'] % api_link), InlineKeyboardButton( queries['albums']['text'], callback_data=queries['albums']['query'] % api_link) ], [ InlineKeyboardButton( queries['radio']['text'], callback_data=queries['radio']['query'] % api_link), InlineKeyboardButton( queries['related']['text'], callback_data=queries['related']['query'] % api_link) ]] image1 = url['picture_xl'] artist = url['name'] albums = url['nb_album'] fans = url['nb_fan'] if any(a in link for a in services_supported[1:]): sendPhoto(chat_id, image1, caption=(send_image_artist_query % (artist, albums, fans)), reply_markup=InlineKeyboardMarkup(keyboard)) else: sendMessage(chat_id, not_supported_links % link) else: sendMessage(chat_id, not_supported_links % link) except FileNotFoundError: sendMessage(chat_id, "Resend link please...", reply_to_message_id=message_id) except error.TimedOut: sendMessage(chat_id, "Retry after a few minutes") except exceptions.QuotaExceeded: sendMessage(chat_id, "Please send the link %s again :(" % link) except exceptions.AlbumNotFound: sendMessage(chat_id, "Album %s didn't find on Deezer :(" % link) sendMessage( chat_id, "Try to search it throught inline mode or search the link on Deezer" ) except Exception as a: logging.error(a) logging.error(quality) logging.error(link) sendMessage( chat_id, "OPS :( Something went wrong please send to @AmineSoukara this link: {} {}, if this happens again" .format(link, quality)) if done == 1: sendMessage(chat_id, end_message, reply_to_message_id=message_id, reply_markup=InlineKeyboardMarkup(end_keyboard)) delete(chat_id)
users = {} date = {} del1 = 0 del2 = 0 free = 1 is_audio = 0 initialize() config = {"key": acrcloud_key, "secret": acrcloud_hash, "host": acrcloud_host} logging.basicConfig( filename="dwsongs.log", level=logging.ERROR, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s") spo = Spotify(generate_token()) def reque(url, chat_id=None, control=False): thing = request(url) if control: try: if thing.json()['error']['message'] == "Quota limit exceeded": sendMessage(chat_id, "Please send the link again :(") return except KeyError: pass try: if thing.json()['error']:
def track(link, chat_id, quality): global spo lin = "track/%s" % link.split("/")[-1] qua = quality.split("MP3_")[-1] query = where_query.format(lin, qua) match = view_db(query) if match: sendAudio(chat_id, match[0]) else: try: youtube = False if "spotify" in link: try: url = spo.track(link) except: spo = Spotify(generate_token()) url = spo.track(link) try: image = url['album']['images'][2]['url'] except IndexError: image = image_resize(song_default_image, 90) mode = downloa.download_trackspo elif "deezer" in link: ids = link.split("/")[-1] api_link = api_track % ids kind = "track" try: url = reque(api_link, chat_id, True).json()['album']['cover_xl'] except AttributeError: return image = image_resize(check_image(url, ids, kind), 90) mode = downloa.download_trackdee z = mode(link, quality=quality, recursive_quality=True, recursive_download=True, not_interface=not_interface) except (exceptions.TrackNotFound, exceptions.NoDataApi): sendMessage( chat_id, "Track doesn't %s exist on Deezer or maybe it isn't readable, it'll be downloaded from YouTube..." % link) try: if "spotify" in link: mode = dwytsongs.download_trackspo elif "deezer" in link: mode = dwytsongs.download_trackdee z = mode(link, recursive_download=True, not_interface=not_interface) youtube = True except: sendMessage(chat_id, "Sorry I cannot download this song %s :(" % link) return image = get_image(image) sendAudio(chat_id, z, link, image, youtube)
from spotipy import Spotify s = Spotify(token) tracks = s.current_user_top_tracks(limit=10) for track in tracks.items: print(track.name) finlandia = '3hHWhvw2hjwfngWcFjIzqr' s.playback_start_tracks([finlandia])
def Audio(audio, chat_id): global spo global is_audio is_audio = 1 audi = "{}{}.ogg".format(loc_dir, audio) try: bot.getFile(audio).download(audi) except TelegramError: sendMessage( chat_id, "File sent is too big, please send a file lower than 20 MB") is_audio = 0 return audio = acrcloud.recognizer(audi) is_audio = 0 try: os.remove(audi) except FileNotFoundError: pass if audio['status']['msg'] != "Success": sendMessage(chat_id, "Sorry cannot detect the song from audio :(, retry...") return infos = audio['metadata']['music'][0] artist = infos['artists'][0]['name'] track = infos['title'] album = infos['album']['name'] try: date = infos['release_date'] album += "_%s" % date except KeyError: album += "_" try: label = infos['label'] album += "_%s" % label except KeyError: album += "_" try: genre = infos['genres'][0]['name'] album += "_%s" % genre except KeyError: album += "_" if len(album) > 64: album = "Infos with too many bytes" try: song = "{} - {}".format(track, artist) url = reque(api_search_trk % song.replace("#", ""), chat_id, True).json() except AttributeError: return try: for a in range(url['total'] + 1): if url['data'][a]['title'] == track: ids = url['data'][a]['link'] image = url['data'][a]['album']['cover_xl'] break except IndexError: try: ids = "https://open.spotify.com/track/%s" % infos[ 'external_metadata']['spotify']['track']['id'] try: url = spo.track(ids) except: spo = Spotify(generate_token()) url = spo.track(ids) image = url['album']['images'][0]['url'] except KeyError: try: ids = api_track % infos['external_metadata']['deezer'][ 'track']['id'] try: url = reque(ids, chat_id, True).json() except AttributeError: return image = url['album']['cover_xl'] except KeyError: sendMessage(chat_id, "Sorry I can't Shazam the track :(") return keyboard = [[ InlineKeyboardButton(queries['download']['text'], callback_data=ids), InlineKeyboardButton(queries['info']['text'], callback_data=album) ]] sendPhoto(chat_id, image, caption="{} - {}".format(track, artist), reply_markup=InlineKeyboardMarkup(keyboard))
app = QApplication([]) app.setQuitOnLastWindowClosed(False) scope = "streaming user-library-read user-modify-playback-state user-read-playback-state user-library-modify " \ "playlist-read-private playlist-read-private playlist-read-collaborative user-follow-read" sp_oauth = oauth2.SpotifyOAuth(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=redirect_uri, scope=scope, username=USERNAME) token_info = sp_oauth.get_access_token(as_dict=True) token = token_info["access_token"] try: sp = Spotify(auth=token) print( f"{colors.PINK}{colors.BOLD}Welcome to Spotlightify{colors.RESET}\n\n") except: print("User token could not be created") exit() def exit_app(): ui.close() # visually removes ui quicker kill(getpid(), 9) def show_ui(): if not ui.isActiveWindow() or ui.isHidden(): ui.show()
async def spotify(self, ctx: Context, url: str = None, type_: str = None): if not url: return await ctx.send(embed=ErrorEmbed( author=ctx.author, title=':x: Missing Spotify link or ID' )) elif not type_: try: type_ = url.split('&')[0].split('?')[0].split('/')[3] except IndexError: pass if type_ == 'user': return await ctx.send(embed=ErrorEmbed( author=ctx.author, title=':x: User profiles are not supported', description='...yet?' )) elif type_ not in ['track', 'album', 'artist', 'playlist']: return await ctx.send(embed=ErrorEmbed( author=ctx.author, title=':x: What is this?', description='Is it `track`, `album`, `artist` or `playlist`?' )) if url.startswith(('http://open.spotify.com', 'https://open.spotify.com')): url = url.split('?')[0].split('/')[-1] type_ = type_.lower() try: sp = Spotify(auth_manager=SpotifyClientCredentials( client_id=spotify_client_id(), client_secret=spotify_client_secret() )) except SpotifyOauthError: sp = None if not sp: return await ctx.send(embed=ErrorEmbed( author=ctx.author, title=':x: Unable to connect to Spotify!' )) result = error_code = None em = SuccessEmbed( author=ctx.author ).set_author( name=f'{ctx.author.display_name} shared a{"n" if type_[0] == "a" else ""} {type_}:', icon_url=ctx.author.avatar_url ) if type_ == 'track': try: result = sp.track(url) except SpotifyException as e: error_code = int(e.http_status) elif type_ == 'album': try: result = sp.album(url) except SpotifyException as e: error_code = int(e.http_status) elif type_ == 'playlist': try: result = sp.playlist(url) except SpotifyException as e: error_code = int(e.http_status) elif type_ == 'artist': try: result = sp.artist(url) except SpotifyException as e: error_code = int(e.http_status) else: return await ctx.send(embed=ErrorEmbed( author=ctx.author, title=':x: Unknown object type', description='Check `>help` for valid object types.' )) if error_code: if error_code == 400: d = 'Invalid ID or URL.' elif error_code == 429: d = 'Unable to do that now, please try again in 5 minutes.' elif str(error_code).startswith('5'): d = 'Spotify is not responding.' else: d = 'Unknown error. Please try again in a few minutes and please make sure URL or ID is valid.' return await ctx.send(embed=ErrorEmbed( author=ctx.author, title=':x: An error occurred!', description=d )) elif not result: return await ctx.send(embed=ErrorEmbed( author=ctx.author, title=':x: Unable to find anything on Spotify', description='Probably URL/ID is wrong.' )) title = result['name'] # Artists if type_ not in ['artist', 'playlist']: artists = list(map(lambda x: [x['name'], x['external_urls']['spotify']], result['artists'])) elif type_ in ['playlist']: artists = [[result['owner']['display_name'], result['owner']['external_urls']['spotify']]] else: artists = None # Released if type_ == 'track': released = result['album']['release_date'] elif type_ == 'album': released = result['release_date'] else: released = None # Genres if type_ in ['artist', 'album']: genres = ', '.join(result['genres']) or 'Not specified' else: genres = None ex_url = result['external_urls']['spotify'] thumbnail = result['album']['images'][0]['url'] if type_ == 'track' else result['images'][0]['url'] # Title if title: em.add_field( name='Name' if type_ in ['artist'] else 'Title', value=title ) # Author / Artist(s) if artists: em.add_field( name='Author' if type_ == 'playlist' else 'Artist' if len(artists) == 1 else 'Artists', value=', '.join(map(lambda x: f'[{x[0]}]({x[1]} "Check it on Spotify")', artists)) ) # Followers if type_ in ['artist', 'playlist']: em.add_field( name='Followers', value=result['followers']['total'] ) # Album if type_ == 'track': em.add_field( name='Album', value=f'[{result["name"]}]({result["album"]["external_urls"]["spotify"]} "Check it on Spotify")' ) # Released if released: em.add_field( name='Released', value=released ) # Tracks if type_ in ['playlist', 'album']: em.add_field( name='Tracks', value=str(result['tracks']['total']) ) # Genres if genres: em.add_field( name='Genres', value=genres ) # Popularity if type_ in ['track', 'artist', 'album']: em.add_field( name='Popularity', value=str(result['popularity']) ) # Label elif type_ == 'album': em.add_field( name='Label', value=result['label'] ) # Spotify link if ex_url: em.add_field( name='Spotify', value=ex_url, inline=False ) # YouTube link if type_ == 'track': # Lookup YouTube query = '{} {}'.format(result['name'], ' '.join(map(lambda x: x['name'], result['artists']))) yt = SearchVideos( query, mode='dict', max_results=1 ).result() # noinspection PyTypeChecker yt = yt['search_result'][0]['link'] if yt else None em.add_field( name='YouTube', value=yt, inline=False ) # Thumbnail if thumbnail: em.set_thumbnail( url=thumbnail ) await ctx.send(embed=em) try: await ctx.message.delete() except Forbidden or NotFound or HTTPException: pass
def __init__(self, token_info): self.token_info = token_info self.sp = Spotify(token_info['access_token'])
import websockets from spotipy import Spotify from spotipy.oauth2 import SpotifyPKCE from params import Params import time from threading import Thread, Event auth_manager = SpotifyPKCE(client_id="a9ed7f99384943dc98518ed396cd639a", redirect_uri="http://localhost:7999/callback", scope="playlist-read-private", open_browser=False) sp = Spotify(auth_manager=auth_manager) event = Event() async def handler(ws, path): event.wait() await ws.send(params.get_queue()) def start_server(): asyncio.set_event_loop(asyncio.new_event_loop()) server = websockets.serve(handler, "0.0.0.0", 7999) asyncio.get_event_loop().run_until_complete(server) asyncio.get_event_loop().run_forever()
def refresh_token(self): self.token_info = spotify_auth.update_token_info(self.token_info) self.sp = Spotify(self.token_info['access_token'])
def test_custom_requests_session(self): sess = requests.Session() sess.headers["user-agent"] = "spotipy-test" with_custom_session = Spotify(auth=self.token, requests_session=sess) self.assertTrue( with_custom_session.user(user="******")["uri"] == "spotify:user:akx")
def track(link, chat_id, quality): global spo conn = connect(db_file) c = conn.cursor() lin = "track/%s" % link.split("/")[-1] qua = quality.split("MP3_")[-1] match = c.execute( where_query.format(lin, qua) ).fetchone() conn.close() if match: sendAudio(chat_id, match[0]) else: try: youtube = False if "spotify" in link: try: url = spo.track(link) except: spo = Spotify( generate_token() ) url = spo.track(link) try: image = url['album']['images'][2]['url'] except IndexError: image = "https://e-cdns-images.dzcdn.net/images/cover/90x90-000000-80-0-0.jpg" z = downloa.download_trackspo( link, quality = quality, recursive_quality = True, recursive_download = True, not_interface = True ) elif "deezer" in link: ids = link.split("/")[-1] try: url = request( "https://api.deezer.com/track/%s" % ids, chat_id, True ).json()['album']['cover_xl'] except AttributeError: return image = check_image(url, ids).replace("1000x1000", "90x90") z = downloa.download_trackdee( link, quality = quality, recursive_quality = True, recursive_download = True, not_interface = True ) except (exceptions.TrackNotFound, exceptions.NoDataApi): sendMessage(chat_id, "Track doesn't %s exist on Deezer or maybe it isn't readable, it'll be downloaded from YouTube..." % link) try: if "spotify" in link: z = dwytsongs.download_trackspo( link, recursive_download = True, not_interface = True ) elif "deezer" in link: z = dwytsongs.download_trackdee( link, recursive_download = True, not_interface = True ) youtube = True except: sendMessage(chat_id, "Sorry I cannot download this song %s :(" % link) return image = request(image).content sendAudio(chat_id, z, link, image, youtube)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Spotify from a config entry.""" implementation = await async_get_config_entry_implementation(hass, entry) session = OAuth2Session(hass, entry, implementation) try: await session.async_ensure_token_valid() except aiohttp.ClientError as err: raise ConfigEntryNotReady from err spotify = Spotify(auth=session.token["access_token"]) try: current_user = await hass.async_add_executor_job(spotify.me) except SpotifyException as err: raise ConfigEntryNotReady from err if not current_user: raise ConfigEntryNotReady async def _update_devices() -> list[dict[str, Any]]: if not session.valid_token: await session.async_ensure_token_valid() await hass.async_add_executor_job( spotify.set_auth, session.token["access_token"] ) try: devices: dict[str, Any] | None = await hass.async_add_executor_job( spotify.devices ) except (requests.RequestException, SpotifyException) as err: raise UpdateFailed from err if devices is None: return [] return devices.get("devices", []) device_coordinator: DataUpdateCoordinator[ list[dict[str, Any]] ] = DataUpdateCoordinator( hass, LOGGER, name=f"{entry.title} Devices", update_interval=timedelta(minutes=5), update_method=_update_devices, ) await device_coordinator.async_config_entry_first_refresh() hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = HomeAssistantSpotifyData( client=spotify, current_user=current_user, devices=device_coordinator, session=session, ) if not set(session.token["scope"].split(" ")).issuperset(SPOTIFY_SCOPES): raise ConfigEntryAuthFailed hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
def Link(link, chat_id, quality, msg): global spo global del1 del1 += 1 done = 0 links1 = [] links2 = [] quali = quality.split("MP3_")[-1] link = link.split("?")[0] try: if "spotify" in link: if "track/" in link: try: url = spo.track(link) except Exception as a: if not "The access token expired" in str(a): sendMessage( chat_id, "Invalid link %s ;)" % link, reply_to_message_id = msg['message_id'] ) delete(chat_id) return spo = Spotify( generate_token() ) url = spo.track(link) try: image1 = url['album']['images'][0]['url'] except IndexError: image1 = "https://e-cdns-images.dzcdn.net/images/cover/1000x1000-000000-80-0-0.jpg" sendPhoto( chat_id, image1, caption = ( send_image_track_query % ( url['name'], url['album']['artists'][0]['name'], url['album']['name'], url['album']['release_date'] ) ) ) track(link, chat_id, quality) elif "album/" in link: try: tracks = spo.album(link) except Exception as a: if not "The access token expired" in str(a): sendMessage( chat_id, "Invalid link %s ;)" % link, reply_to_message_id = msg['message_id'] ) delete(chat_id) return spo = Spotify( generate_token() ) tracks = spo.album(link) try: image3 = tracks['images'][2]['url'] image2 = tracks['images'][1]['url'] image1 = tracks['images'][0]['url'] except IndexError: image3 = "https://e-cdns-images.dzcdn.net/images/cover/90x90-000000-80-0-0.jpg" image2 = "https://e-cdns-images.dzcdn.net/images/cover/320x320-000000-80-0-0.jpg" image1 = "https://e-cdns-images.dzcdn.net/images/cover/1000x1000-000000-80-0-0.jpg" tot = tracks['total_tracks'] conn = connect(db_file) c = conn.cursor() lin = "album/%s" % link.split("/")[-1] count = [0] sendPhoto( chat_id, image1, caption = ( send_image_album_query % ( tracks['name'], tracks['artists'][0]['name'], tracks['release_date'], tot ) ) ) def lazy(a): count[0] += a['duration_ms'] lin = "track/%s" % a['external_urls']['spotify'].split("/")[-1] c.execute( where_query.format(lin, quali) ) links2.append(lin) if c.fetchone(): links1.append(lin) for a in tracks['tracks']['items']: lazy(a) tracks = tracks['tracks'] if tot != 50: for a in range(tot // 50): try: tracks = spo.next(tracks) except: spo = Spotify( generate_token() ) tracks = spo.next(tracks) for a in tracks['items']: lazy(a) conn.close() if (count[0] / 1000) > 40000: sendMessage(chat_id, "If you do this again I will come to your home and I will ddos your ass :)") delete(chat_id) return if len(links1) != tot: z = downloa.download_albumspo( link, quality = quality, recursive_quality = True, recursive_download = True, not_interface = True ) else: for a in links2: track(a, chat_id, quality) done = 1 elif "playlist/" in link: musi = link.split("/") try: tracks = spo.user_playlist(musi[-3], musi[-1]) except Exception as a: if not "The access token expired" in str(a): sendMessage( chat_id, "Invalid link ;)", reply_to_message_id = msg['message_id'] ) delete(chat_id) return spo = Spotify( generate_token() ) tracks = spo.user_playlist(musi[-3], musi[-1]) try: image1 = tracks['images'][0]['url'] except IndexError: image1 = "https://e-cdns-images.dzcdn.net/images/cover/1000x1000-000000-80-0-0.jpg" tot = tracks['tracks']['total'] if tot > 400: sendMessage(chat_id, "F**k you") delete(chat_id) return sendPhoto( chat_id, image1, caption = ( send_image_playlist_query % ( tracks['tracks']['items'][0]['added_at'], tracks['owner']['display_name'], tot ) ) ) def lazy(a): try: track( a['track']['external_urls']['spotify'], chat_id, quality ) except: try: sendMessage(chat_id, "%s Not found :(" % a['track']['name']) except: sendMessage(chat_id, "Error :(") for a in tracks['tracks']['items']: lazy(a) tot = tracks['tracks']['total'] tracks = tracks['tracks'] if tot != 100: for a in range(tot // 100): try: tracks = spo.next(tracks) except: spo = Spotify( generate_token() ) tracks = spo.next(tracks) for a in tracks['items']: lazy(a) done = 1 else: sendMessage(chat_id, "Sorry :( The bot doesn't support this link") elif "deezer" in link: ids = link.split("/")[-1] if "track/" in link: try: url = request( "https://api.deezer.com/track/%s" % ids, chat_id, True ).json() except AttributeError: delete(chat_id) return image1 = check_image( url['album']['cover_xl'], ids ) sendPhoto( chat_id, image1, caption = ( send_image_track_query % ( url['title'], url['artist']['name'], url['album']['title'], url['album']['release_date'] ) ) ) track(link, chat_id, quality) elif "album/" in link: try: url = request( "https://api.deezer.com/album/%s" % ids, chat_id, True ).json() except AttributeError: delete(chat_id) return if url['duration'] > 40000: sendMessage(chat_id, "If you do this again I will come to your home and I will ddos your ass :)") delete(chat_id) return image1 = url['cover_xl'] if not image1: URL = "https://www.deezer.com/album/%s" % ids image1 = request(URL).text image1 = ( BeautifulSoup(image1, "html.parser") .find("img", class_ = "img_main") .get("src") .replace("200x200", "1000x1000") ) ima = request(image1).content if len(ima) == 13: image1 = "https://e-cdns-images.dzcdn.net/images/cover/1000x1000-000000-80-0-0.jpg" image2 = image1.replace("1000x1000", "320x320") image3 = image1.replace("1000x1000", "90x90") conn = connect(db_file) c = conn.cursor() lin = "album/%s" % ids for a in url['tracks']['data']: lin = "track/%s" % a['link'].split("/")[-1] c.execute( where_query.format(lin, quali) ) links2.append(lin) if c.fetchone(): links1.append(lin) conn.close() tot = url['nb_tracks'] sendPhoto( chat_id, image1, caption = ( send_image_album_query % ( url['title'], url['artist']['name'], url['release_date'], tot ) ) ) if len(links1) != tot: z = downloa.download_albumdee( link, quality = quality, recursive_quality = True, recursive_download = True, not_interface = True ) else: for a in links2: track(a, chat_id, quality) done = 1 elif "playlist/" in link: try: url = request( "https://api.deezer.com/playlist/%s" % ids, chat_id, True ).json() except AttributeError: delete(chat_id) return tot = url['nb_tracks'] if tot > 400: sendMessage(chat_id, "F**k you") delete(chat_id) return sendPhoto( chat_id, url['picture_xl'], caption = ( send_image_playlist_query % ( url['creation_date'], url['creator']['name'], tot ) ) ) for a in url['tracks']['data']: try: track(a['link'], chat_id, quality) except: song = "{} - {}".format(a['title'], a['artist']['name']) sendMessage(chat_id, "Cannot download %s :(" % song) done = 1 elif "artist/" in link: link = "https://api.deezer.com/artist/%s" % ids try: url = request(link, chat_id, True).json() except AttributeError: delete(chat_id) return sendPhoto( chat_id, url['picture_xl'], caption = ( "👤 Artist: %s \n💽 Album numbers: %d \n👥 Fans on Deezer: %d" % ( url['name'], url['nb_album'], url['nb_fan'] ) ), reply_markup = InlineKeyboardMarkup( inline_keyboard = [ [ InlineKeyboardButton( text = "TOP 30 🔝", callback_data = "%s/top?limit=30" % link ), InlineKeyboardButton( text = "ALBUMS 💽", callback_data = "%s/albums" % link ) ], [ InlineKeyboardButton( text = "RADIO 📻", callback_data = "%s/radio" % link ), InlineKeyboardButton( text = "RELATED 🗣", callback_data = "%s/related" % link ) ] ] ) ) else: sendMessage(chat_id, "Sorry :( The bot doesn't support this link %s :(" % link) else: sendMessage(chat_id, "Sorry :( The bot doesn't support this link %s :(" % link) try: image3 = request(image3).content for a in range( len(z) ): sendAudio(chat_id, z[a], links2[a], image3) except NameError: pass except exceptions.QuotaExceeded: sendMessage(chat_id, "Please send the link %s again :(" % link) except exceptions.AlbumNotFound: sendMessage(chat_id, "Album %s didn't find on Deezer :(" % link) sendMessage(chat_id, "Try to search it throught inline mode or search the link on Deezer") except Exception as a: logging.warning(a) logging.warning(quality) logging.warning(link) sendMessage( chat_id, "OPS :( Something went wrong please send to @An0nimia this link: {} {}, if this happens again".format(link, quality) ) if done == 1: sendMessage( chat_id, "FINISHED :) Rate me here https://t.me/BotsArchive/298", reply_to_message_id = msg['message_id'], reply_markup = InlineKeyboardMarkup( inline_keyboard = [ [ InlineKeyboardButton( text = "SHARE", url = "tg://msg?text=Start @%s for download all the songs which you want ;)" % bot_name ) ] ] ) ) delete(chat_id)
def setUpClass(cls): username = os.getenv(CCEV['client_username']) token = prompt_for_user_token(username) cls.spotify = Spotify(auth=token)
def __init__(self): self.hue_bridge = Bridge(credentials.hue_bridge_ip_address) self.spotify = Spotify(auth=spotipy.util.prompt_for_user_token( credentials.spotify_username, credentials.spotify_scope, credentials.spotify_client_id, credentials.spotify_client_secret, credentials.spotify_redirect_uri))