Python spotipy.Spotify() Examples

The following are 30 code examples of spotipy.Spotify(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module spotipy , or try the search function .
Example #1
Source File: spotify.py    From spotify-downloader with MIT License 8 votes vote down vote up
def write_album_tracks(self, album, target_path=None):
        """
        Writes album track URIs to file.

        Parameters
        ----------
        album: `dict`
            Spotify API response object for the album endpoint.

        target_path: `str`
            Write Spotify track URIs to this file.
        """
        tracks = self.spotify.album_tracks(album["id"])
        if not target_path:
            target_path = u"{0}.txt".format(slugify(album["name"], ok="-_()[]{}"))
        return self.write_tracks(tracks, target_path) 
Example #2
Source File: spotify.py    From spotify-downloader with MIT License 7 votes vote down vote up
def prompt_for_user_playlist(self, username):
        """
        An interactive method that will display user's playlists
        and prompt to make a selection.

        Parameters
        ----------
        username: `str`
            Spotfiy username.

        Returns
        -------
        spotify_uri: `str`
            Spotify URI for the selected playlist.
        """
        playlists = self.fetch_user_playlist_urls(username)
        for i, playlist in enumerate(playlists, 1):
            playlist_details = "{0}. {1:<30}  ({2} tracks)".format(
                i, playlist["name"], playlist["tracks"]["total"]
            )
            print(playlist_details, file=sys.stderr)
        print("", file=sys.stderr)
        playlist = spotdl.util.prompt_user_for_selection(playlists)
        return playlist["external_urls"]["spotify"] 
Example #3
Source File: musictools.py    From MusicTools with MIT License 7 votes vote down vote up
def get_metadata(file_name, client_id, client_secret):
    """
    Tries finding metadata through Spotify
    """

    song_name = improve_name(file_name)  # Remove useless words from title
    client_credentials_manager = SpotifyClientCredentials(client_id, client_secret)

    spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
    results = spotify.search(song_name, limit=1)

    results = results['tracks']['items'][0]  # Find top result
    album = results['album']['name']  # Parse json dictionary
    artist = results['album']['artists'][0]['name']
    song_title = results['name']
    album_art = results['album']['images'][0]['url']

    return artist, album, song_title, album_art 
Example #4
Source File: spotify.py    From smd with MIT License 6 votes vote down vote up
def __init__(self):

        '''
       Init function
       Creating spotify object with access_token
       :return: None
       '''

        self.__url = 'https://accounts.spotify.com/api/token'
        self.__grant_type = 'client_credentials'
        self.__body_params = {
            'grant_type': self.__grant_type
            }

        self.__getData()
        self.__getAccessToken()

        #initialization of spotify client
        self.client = spotipy.Spotify(self.__access_token)
        #sys.exit() 
Example #5
Source File: spotify.py    From spotify-downloader with MIT License 6 votes vote down vote up
def write_all_albums(self, albums, target_path=None):
        """
        Writes tracks from all albums into a file.

        Parameters
        ----------
        albums: `str`
            Spotfiy API response received in :func:`fetch_albums_from_artist`.

        target_path: `str`
            Write Spotify track URIs to this file.
        """
        # if no file if given, the default save file is in the current working
        # directory with the name of the artist
        if target_path is None:
            target_path = albums[0]["artists"][0]["name"] + ".txt"

        for album in albums:
            logger.info('Fetching album "{album}".'.format(album=album["name"]))
            self.write_album_tracks(album, target_path=target_path) 
Example #6
Source File: spotify.py    From spotify-downloader with MIT License 6 votes vote down vote up
def fetch_album(self, album_uri):
        """
        Fetches album.

        Parameters
        ----------
        album_uri: `str`
            Spotify album URI.

        Returns
        -------
        album: `dict`
            Spotify API response object for the album endpoint.
        """
        logger.debug('Fetching album "{album}".'.format(album=album_uri))
        try:
            album = self.spotify.album(album_uri)
        except spotipy.client.SpotifyException:
            msg = ('Unable to find album "{}". Make sure the album ID is correct '
                   'and then try again.'.format(album_uri))
            logger.error(msg)
            raise spotdl.helpers.exceptions.SpotifyAlbumNotFoundError(msg)
        else:
            return album 
Example #7
Source File: spotify.py    From spotify-downloader with MIT License 6 votes vote down vote up
def write_playlist_tracks(self, playlist, target_path=None):
        """
        Writes playlist track URIs to file.

        Parameters
        ----------
        playlist: `dict`
            Spotify API response object for the playlist endpoint.

        target_path: `str`
            Write Spotify track URIs to this file.
        """
        tracks = playlist["tracks"]
        if not target_path:
            target_path = u"{0}.txt".format(slugify(playlist["name"], ok="-_()[]{}"))
        return self.write_tracks(tracks, target_path) 
Example #8
Source File: auth.py    From spotify-onthego with GNU General Public License v3.0 6 votes vote down vote up
def ask_for_credentials(**credentials_found):
    print(
        """You need to register as a developer and create a Spotify app in order to use spotify-onthego.
You may create an app here: https://developer.spotify.com/my-applications/#!/applications/create
You also need to register a youtube app developer key. The app key can be
obtained for free here: https://console.cloud.google.com/apis/api/youtube/overview
Please enter your app credentials:"""
    )
    username = credentials_found.get("USERNAME") or input("Spotify username: ")
    client_id = credentials_found.get("CLIENT_ID") or input("Spotify client ID: ")
    client_secret = credentials_found.get("CLIENT_SECRET") or input(
        "Spotify client secret: "
    )
    redirect_uri = credentials_found.get("REDIRECT_URI") or input(
        "Spotify redirect URI: "
    )
    google_developer_key = credentials_found.get("GOOGLE_DEVELOPER_KEY") or input(
        "Google developer key: "
    )
    return username, client_id, client_secret, redirect_uri, google_developer_key 
Example #9
Source File: auth.py    From spotify-onthego with GNU General Public License v3.0 6 votes vote down vote up
def save_credentials(
    username, client_id, client_secret, redirect_uri, google_developer_key
):
    credentials_path = get_credentials_path()
    print("Saving Spotify and Youtube credentials to", credentials_path)
    check_directory_exists(credentials_path)
    with open(credentials_path, "w") as credentials_file:
        json.dump(
            {
                "USERNAME": username,
                "CLIENT_ID": client_id,
                "CLIENT_SECRET": client_secret,
                "REDIRECT_URI": redirect_uri,
                "GOOGLE_DEVELOPER_KEY": google_developer_key,
            },
            credentials_file,
        ) 
Example #10
Source File: utils.py    From plugin.audio.spotify with GNU General Public License v3.0 6 votes vote down vote up
def get_token(spotty):
    # get authentication token for api - prefer cached version
    token_info = None
    try:
        if spotty.playback_supported:
            # try to get a token with spotty
            token_info = request_token_spotty(spotty, use_creds=False)
            if token_info:
                spotty.get_username() # save current username in cached spotty creds
            if not token_info:
                token_info = request_token_spotty(spotty, use_creds=True)
        else:
            # request new token with web flow
            token_info = request_token_web()
    except Exception as exc:
        log_exception("utils.get_token", exc)
        token_info = None
    if not token_info:
        log_msg("Couldn't request authentication token. Username/password error ? "
                "If you're using a facebook account with Spotify, "
                "make sure to generate a device account/password in the Spotify accountdetails.")
    return token_info 
Example #11
Source File: main_service.py    From plugin.audio.spotify with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        self.addon = xbmcaddon.Addon(id=ADDON_ID)
        self.win = xbmcgui.Window(10000)
        self.kodimonitor = xbmc.Monitor()
        self.spotty = Spotty()

        # spotipy and the webservice are always prestarted in the background
        # the auth key for spotipy will be set afterwards
        # the webserver is also used for the authentication callbacks from spotify api
        self.sp = spotipy.Spotify()
        self.connect_player = ConnectPlayer(sp=self.sp, spotty=self.spotty)

        self.proxy_runner = ProxyRunner(self.spotty)
        self.proxy_runner.start()
        webport = self.proxy_runner.get_port()
        log_msg('started webproxy at port {0}'.format(webport))

        # authenticate at startup
        self.renew_token()

        # start mainloop
        self.main_loop() 
Example #12
Source File: client.py    From plugin.audio.spotify with GNU General Public License v3.0 6 votes vote down vote up
def user_playlist_remove_specific_occurrences_of_tracks(
            self, user, playlist_id, tracks, snapshot_id=None):
        ''' Removes all occurrences of the given tracks from the given playlist

            Parameters:
                - user - the id of the user
                - playlist_id - the id of the playlist
                - tracks - an array of objects containing Spotify URIs of the tracks to remove with their current positions in the playlist.  For example:
                    [  { "uri":"4iV5W9uYEdYUVa79Axb7Rh", "positions":[2] },
                       { "uri":"1301WleyT98MSxVHPZCA6M", "positions":[7] } ]
                - snapshot_id - optional id of the playlist snapshot
        '''

        plid = self._get_id('playlist', playlist_id)
        ftracks = []
        for tr in tracks:
            ftracks.append({
                "uri": self._get_uri("track", tr["uri"]),
                "positions": tr["positions"],
            })
        payload = {"tracks": ftracks}
        if snapshot_id:
            payload["snapshot_id"] = snapshot_id
        return self._delete("users/%s/playlists/%s/tracks" % (user, plid),
                            payload=payload) 
Example #13
Source File: client.py    From plugin.audio.spotify with GNU General Public License v3.0 6 votes vote down vote up
def category_playlists(self, category_id=None, country=None, limit=20,
                           offset=0):
        ''' Get a list of new album releases featured in Spotify

            Parameters:
                - category_id - The Spotify category ID for the category.

                - country - An ISO 3166-1 alpha-2 country code.

                - limit - The maximum number of items to return. Default: 20.
                  Minimum: 1. Maximum: 50

                - offset - The index of the first item to return. Default: 0
                  (the first object). Use with limit to get the next set of
                  items.
        '''
        return self._get('browse/categories/' + category_id + '/playlists',
                         country=country, limit=limit, offset=offset) 
Example #14
Source File: plugin_content.py    From plugin.audio.spotify with GNU General Public License v3.0 6 votes vote down vote up
def __next__(self):
        # For the most part, the buffer-filling thread should prevent the need for waiting here,
        # but wait exponentially (up to about 32 seconds) for it to fill before giving up.
        log_msg("Spotify radio track buffer asked for next item", xbmc.LOGDEBUG)
        attempts = 0
        while attempts <= 5:
            self._buffer_lock.acquire()
            if len(self._buffer) <= self.MIN_BUFFER_SIZE:
                self._buffer_lock.release()
                sleep_time = pow(2, attempts)
                log_msg("Spotify radio track buffer empty, sleeping for %d seconds" % sleep_time, xbmc.LOGDEBUG)
                time.sleep(sleep_time)
                attempts += 1
            else:
                track = self._buffer.pop(0)
                self._buffer_lock.release()
                log_msg("Got track '%s' from Spotify radio track buffer" % track["id"], xbmc.LOGDEBUG)
                return track
        raise StopIteration

    # Support both Python 2.7 & Python 3.0 
Example #15
Source File: spotify.py    From smd with MIT License 6 votes vote down vote up
def __init__(self):

        '''
       Init function
       Creating spotify object with access_token
       :return: None
       '''

        self.__url = 'https://accounts.spotify.com/api/token'
        self.__grant_type = 'client_credentials'
        self.__body_params = {
            'grant_type': self.__grant_type
            }

        self.__getData()
        self.__getAccessToken()

        #initialization of spotify client
        self.client = spotipy.Spotify(self.__access_token)
        #sys.exit() 
Example #16
Source File: spotify.py    From smd with MIT License 6 votes vote down vote up
def __init__(self, server):

            self.__grant_type = 'authorization_code'
            self.__scope = '''
                user-library-read,
                user-top-read,
                user-follow-read,
                playlist-read-private,
                playlist-read-collaborative,
                user-read-recently-played
            '''
            self.server = server
            self.__getData()
            self.__redirect = 'http://localhost:5000/'
            self.__urlCode = f'https://accounts.spotify.com/authorize?client_id={self.__client_id}&response_type=code&redirect_uri={self.__redirect}&scope={self.__scope}'
            self.__url = 'https://accounts.spotify.com/api/token'
            self.__image = 'https://raw.githubusercontent.com/artyshko/smd/telegram/Data/9.png'

            if not self.server:

                self.__getRefreshToken()

                self.__client = spotipy.Spotify(auth=self.__access_token) 
Example #17
Source File: library.py    From mopidy-spotify-web with Apache License 2.0 6 votes vote down vote up
def spotify_browse_process_results(results):
    logger.debug('Processing spotify browse result')
    if 'categories' in results:
        result_list = results['categories']
        browse_uri = 'spotifyweb:browse:categories:'
        arr = [Ref.directory(uri=browse_uri + cat['id'],
                             name=cat['name'])
               for cat in result_list['items']]
    elif 'playlists' in results:
        result_list = results['playlists']
        arr = [Ref.playlist(uri=playlist['uri'],
                            name=playlist['name'])
               for playlist in result_list['items']]
    elif 'albums' in results:
        result_list = results['albums']
        arr = [Ref.album(uri=album['uri'],
                         name=album['name'])
               for album in result_list['items']]
    else:
        result_list = None
        arr = []

    cont = result_list is not None and result_list['next'] is not None
    logger.debug('Spotify browse result cont: %s' % cont)
    return arr, cont 
Example #18
Source File: fresh.py    From fresh_script with MIT License 6 votes vote down vote up
def createUserConfig(user, config_path='.config.ini'):
    """
    Create .config.ini file for Spotify credentials.

    Parameters
    ----------
    user: User object
        Spotify user object.

    config_path: str
        Path to .config.ini.

    """
    s_config = ConfigParser()
    s_config['spotify'] = {
        'client_id': user.client_id,
        'client_secret': user.client_secret,
        'username': user.username,
        'playlist_id': user.getPlaylistsAsString(),
        'redirect_uri': user.redirect
    }

    with open(config_path, 'w') as f:
        s_config.write(f) 
Example #19
Source File: plugin_content.py    From plugin.audio.spotify with GNU General Public License v3.0 6 votes vote down vote up
def precache_library(self):
        if not self.win.getProperty("Spotify.PreCachedItems"):
            monitor = xbmc.Monitor()
            self.win.setProperty("Spotify.PreCachedItems", "busy")
            userplaylists = self.get_user_playlists(self.userid)
            for playlist in userplaylists:
                self.get_playlist_details(playlist['owner']['id'], playlist["id"])
                if monitor.abortRequested():
                    return
            self.get_savedalbums()
            if monitor.abortRequested():
                return
            self.get_savedartists()
            if monitor.abortRequested():
                return
            self.get_saved_tracks()
            del monitor
            self.win.setProperty("Spotify.PreCachedItems", "done") 
Example #20
Source File: plugin_content.py    From plugin.audio.spotify with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        try:
            self.addon = xbmcaddon.Addon(id=ADDON_ID)
            self.win = xbmcgui.Window(10000)
            self.cache = SimpleCache()
            auth_token = self.get_authkey()
            if auth_token:
                self.parse_params()
                self.sp = spotipy.Spotify(auth=auth_token)
                self.userid = self.win.getProperty("spotify-username").decode("utf-8")
                self.usercountry = self.win.getProperty("spotify-country").decode("utf-8")
                self.local_playback, self.playername, self.connect_id = self.active_playback_device()
                if self.action:
                    action = "self." + self.action
                    eval(action)()
                else:
                    self.browse_main()
                    self.precache_library()
            else:
                xbmcplugin.endOfDirectory(handle=self.addon_handle)
        except Exception as exc:
            log_exception(__name__, exc)
            xbmcplugin.endOfDirectory(handle=self.addon_handle) 
Example #21
Source File: client.py    From plugin.audio.spotify with GNU General Public License v3.0 6 votes vote down vote up
def categories(self, country=None, locale=None, limit=20, offset=0):
        ''' Get a list of new album releases featured in Spotify

            Parameters:
                - country - An ISO 3166-1 alpha-2 country code.
                - locale - The desired language, consisting of an ISO 639
                  language code and an ISO 3166-1 alpha-2 country code, joined
                  by an underscore.

                - limit - The maximum number of items to return. Default: 20.
                  Minimum: 1. Maximum: 50

                - offset - The index of the first item to return. Default: 0
                  (the first object). Use with limit to get the next set of
                  items.
        '''
        return self._get('browse/categories', country=country, locale=locale,
                         limit=limit, offset=offset) 
Example #22
Source File: spotify_plugs.py    From pbl with MIT License 5 votes vote down vote up
def _get_auth_spotify(user):
    # deprecated
    global auth_sp
    if auth_sp == None:
        scope = 'playlist-modify-public playlist-modify-private'
        token = spotipy.util.prompt_for_user_token(user, scope)
        if token:
            auth_sp = spotipy.Spotify(auth=token)

    return auth_sp 
Example #23
Source File: library.py    From mopidy-spotify-web with Apache License 2.0 5 votes vote down vote up
def spotify_get_tracks_process_results(results):
    logger.debug('Processing spotify get tracks result')
    tracks = [to_mopidy_track(item['track'])
              for item in results['items']]
    cont = results['next'] is not None
    logger.debug('Spotify get tracks result cont: %s' % cont)
    return tracks, cont 
Example #24
Source File: spotify_plugs.py    From pbl with MIT License 5 votes vote down vote up
def _get_spotify():
    spotify = engine.getEnv('spotify')
    if spotify == None:
        auth_token = engine.getEnv('spotify_auth_token')
        if auth_token:
            spotify = spotipy.Spotify(auth=auth_token)
        else:
            spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
        spotify.trace_out = True
        engine.setEnv('spotify', spotify)
    return spotify 
Example #25
Source File: sensor.py    From SmartHouse with MIT License 5 votes vote down vote up
def update(self):
    LOGGER.info("Updating sensor information using spotify api")
    self._prepare_player()

    self._state = STATE_OFF

    if self._player is None:
      LOGGER.warning("Player is disabled")
      return

    if self._token_expired():
      LOGGER.warning("Spotify failed to update, token expired.")
      return 

    current = self._player.current_playback()
    if current is None:
      return

    if current.get('is_playing'):
      item = current.get('item')
      self._state = item.get('album').get('id')
      album_id = item.get('album').get('id')
      cover_url = item.get('album').get('images')[-2].get('url')
      
      self._state = STATE_ON

      colors = self._fetch_colors(album_id, cover_url)
      self._dominant_color = colors['dominant']
      self._accent_color_1 = colors['accent_1']
      self._accent_color_2 = colors['accent_2']
      self._accent_color_3 = colors['accent_3'] 
Example #26
Source File: spotify_plugs.py    From pbl with MIT License 5 votes vote down vote up
def __init__(self, source, playlist_name= None, user=None, uri=None, \
        create=False, append=False, max_size=100):
        self.source = source
        self.uri = normalize_uri(uri)
        self.user = user
        self.name = 'Spotify Save'
        self.playlist_name = playlist_name
        self.max_size = max_size
        self.append = append
        self.create = create
        self.buffer = []
        self.saved = False 
Example #27
Source File: qrgen.py    From qrocodile with MIT License 5 votes vote down vote up
def process_spotify_track(uri, index):
    if not sp:
        raise ValueError('Must configure Spotify API access first using `--spotify-username`')

    track = sp.track(uri)

    print track
    # print 'track    : ' + track['name']
    # print 'artist   : ' + track['artists'][0]['name']
    # print 'album    : ' + track['album']['name']
    # print 'cover art: ' + track['album']['images'][0]['url']
    
    song = strip_title_junk(track['name'])
    artist = strip_title_junk(track['artists'][0]['name'])
    album = strip_title_junk(track['album']['name'])
    arturl = track['album']['images'][0]['url']
    
    # Determine the output image file names
    qrout = 'out/{0}qr.png'.format(index)
    artout = 'out/{0}art.jpg'.format(index)
    
    # Create a QR code from the track URI
    print subprocess.check_output(['qrencode', '-o', qrout, uri])

    # Fetch the artwork and save to the output directory
    print subprocess.check_output(['curl', arturl, '-o', artout])

    return (song.encode('utf-8'), album.encode('utf-8'), artist.encode('utf-8')) 
Example #28
Source File: spotify.py    From hangoutsbot with GNU Affero General Public License v3.0 5 votes vote down vote up
def spotify_client(bot):
    """Spotify access requires user authorization. The refresh token is stored
    in memory to circumvent logging in after the initial authorization."""
    try:
        spotify_client_id = bot.config.get_by_path(
            ["spotify", "spotify", "client_id"])
        spotify_client_secret = bot.config.get_by_path(
            ["spotify", "spotify", "client_secret"])
        spotify_redirect_uri = bot.config.get_by_path(
            ["spotify", "spotify", "redirect_uri"])
        spotify_user = bot.config.get_by_path(["spotify", "spotify", "user"])
    except (KeyError, TypeError) as e:
        logger.error("<b>Spotify authorization isn't configured:</b> {}"
                     .format(e))
        return None

    if bot.memory.exists(["spotify", "token"]):
        old_spotify_token = bot.memory.get_by_path(["spotify", "token"])
    else:
        old_spotify_token = ""

    spotify_token = spotipy.util.prompt_for_user_token(
        spotify_user,
        scope="playlist-modify-public playlist-modify-private",
        client_id=spotify_client_id,
        client_secret=spotify_client_secret,
        redirect_uri=spotify_redirect_uri)

    if old_spotify_token and old_spotify_token != spotify_token:
        bot.memory.set_by_path(["spotify", "token"], spotify_token)

    return spotipy.Spotify(auth=spotify_token) 
Example #29
Source File: repair.py    From MusicNow with MIT License 5 votes vote down vote up
def get_details_spotify(song_name):
    '''
    Tries finding metadata through Spotify
    '''

    song_name = improvename.songname(song_name)

    spotify = spotipy.Spotify()
    results = spotify.search(song_name, limit=1)  # Find top result

    log.log_indented('* Finding metadata from Spotify.')

    try:
        album = (results['tracks']['items'][0]['album']
                 ['name'])  # Parse json dictionary
        artist = (results['tracks']['items'][0]['album']['artists'][0]['name'])
        song_title = (results['tracks']['items'][0]['name'])
        try:
            log_indented("* Finding lyrics from Genius.com")
            lyrics = get_lyrics_genius(song_title)
        except:
            log_error("* Could not find lyrics from Genius.com, trying something else")
            lyrics = get_lyrics_letssingit(song_title)

        match_bool, score = matching_details(song_name, song_title, artist)
        if match_bool:
            return artist, album, song_title, lyrics, match_bool, score
        else:
            return None

    except IndexError:
        log.log_error(
            '* Could not find metadata from spotify, trying something else.', indented=True)
        return None 
Example #30
Source File: command_line.py    From MusicNow with MIT License 5 votes vote down vote up
def get_tracks_from_album(album_name):
    '''
    Gets tracks from an album using Spotify's API
    '''

    spotify = spotipy.Spotify()

    album = spotify.search(q='album:' + album_name, limit=1)
    album_id = album['tracks']['items'][0]['album']['id']
    results = spotify.album_tracks(album_id=str(album_id))
    songs = []
    for items in results['items']:
        songs.append(items['name'])

    return songs