예제 #1
0
    def test_get_authorize_url_does_not_show_dialog_by_default(self):
        oauth = SpotifyOAuth("CLID", "CLISEC", "REDIR")

        url = oauth.get_authorize_url()

        parsed_url = urllibparse.urlparse(url)
        parsed_qs = urllibparse.parse_qs(parsed_url.query)
        self.assertNotIn('show_dialog', parsed_qs)
예제 #2
0
    def test_get_authorize_url_shows_dialog_when_requested(self):
        oauth = SpotifyOAuth("CLID", "CLISEC", "REDIR")

        url = oauth.get_authorize_url(show_dialog=True)

        parsed_url = urllibparse.urlparse(url)
        parsed_qs = urllibparse.parse_qs(parsed_url.query)
        self.assertTrue(parsed_qs['show_dialog'])
예제 #3
0
    def test_get_authorize_url_passes_state_from_func_call(self):
        state = "STATE"
        oauth = SpotifyOAuth("CLID", "CLISEC", "REDIR", "NOT STATE")

        url = oauth.get_authorize_url(state=state)

        parsed_url = urllibparse.urlparse(url)
        parsed_qs = urllibparse.parse_qs(parsed_url.query)
        self.assertEqual(parsed_qs['state'][0], state)
예제 #4
0
    def test_saves_to_cache_path(self, opener):
        scope = "playlist-modify-private"
        path = ".cache-username"
        tok = _make_fake_token(1, 1, scope)

        fi = _fake_file()
        opener.return_value = fi

        spot = SpotifyOAuth("CLID", "CLISEC", "REDIR", "STATE", scope, path)
        spot._save_token_info(tok)

        opener.assert_called_with(path, 'w')
        self.assertTrue(fi.write.called)
 def get_token(self, allow_raw_input=True):
     if allow_raw_input:
         token = util.prompt_for_user_token(
             self.username, config.SCOPE, self.client_id,
             self.client_secret, self.callback_url)
     else:
         sp_oauth = SpotifyOAuth(
             self.client_id, self.client_secret, self.callback_url,
             scope=config.SCOPE, cache_path=self.cache_path)
         token_info = sp_oauth.get_cached_token()
         if token_info:
             token = token_info['access_token']
         else:
             raise Exception('need to run debug-refresh-token in a terminal')
     return token
예제 #6
0
 def __init__(self):
     load_dotenv()
     self._scopes = 'user-read-currently-playing user-read-playback-state'
     self._sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
         scope=self._scopes))
예제 #7
0
def generate_auth_url():
    auth_manager = SpotifyOAuth(scope=scope, cache_path=cache_path)
    url = auth_manager.get_authorize_url()
    return auth_manager, url
예제 #8
0
from spotipy.oauth2 import SpotifyOAuth
from tqdm import trange, tqdm

# params
# for client id and secret, create a new application over at https://developer.spotify.com/dashboard
# when running this script for the first time, your browser will be redirected to grant authorization to this script
# to really delete the songs, set DRYRUN to False
CLIENT_ID = ""
CLIENT_SECRET = ""
REDIRECT_URI = "http://localhost:8888/callback"
DRYRUN = True

# setup
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
    client_id=CLIENT_ID,
    client_secret=CLIENT_SECRET,
    redirect_uri=REDIRECT_URI,
    scope="user-library-read playlist-modify-private user-library-modify"))

# collect metainfo
saved_tracks_metainfo = sp.current_user_saved_tracks()
print("Total liked songs:", saved_tracks_metainfo['total'])

print("Collecting liked songs...")
query_offset = 50
saved_tracks = []
albums = {}
tracks = {}
tracks_to_delete = {}
albums_to_delete = {}
for i in trange(math.ceil(saved_tracks_metainfo['total'] / query_offset)):
예제 #9
0
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from config.spotify_client_credentials import CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, USERNAME, SCOPE

# Initialise Spotify API by passing app credentials and required scope (authorisation code flow)
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=SCOPE,
                                               client_id=CLIENT_ID,
                                               client_secret=CLIENT_SECRET,
                                               redirect_uri=REDIRECT_URI,
                                               username=USERNAME))
예제 #10
0
import spotipy
from credentials import CLIENT_ID, CLIENT_SECRET, REDIRECT_URI
from spotipy.oauth2 import SpotifyOAuth

if __name__ == "__main__":

    scope = "user-read-currently-playing"

    sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
        scope=scope,
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        cache_path="../.cache-willfurtado",
        redirect_uri=REDIRECT_URI,
    ))

    try:
        curr_song_meta = sp.currently_playing(market=None)
        curr_song_name, curr_artist_name = (
            curr_song_meta["item"]["name"],
            curr_song_meta["item"]["artists"][0]["name"],
        )
        curr_user = sp.current_user()["display_name"]
        print(
            "\n" * 5,
            curr_user,
            "is listening to {} by {}".format(curr_song_name,
                                              curr_artist_name),
        )
        print("\n" * 5)
예제 #11
0
import spotipy
from spotipy.oauth2 import SpotifyOAuth

import config

auth_manager = SpotifyOAuth(config.client_id,
                            config.client_secret,
                            redirect_uri=config.redirect_uri,
                            scope=config.scope)

sp = spotipy.Spotify(auth_manager=auth_manager)

artists = sp.current_user_top_artists(limit=20, time_range='short_term')

for i, artist in enumerate(artists['items']):
    similar_artists = sp.artist_related_artists(artist['id'])
    for similar in enumerate(similar_artists):
        print(similar)
예제 #12
0
def get_new_spotify_playlist(username):
    """
  
  """
    user = UserModel.get_user_by_name(username)

    # # delete .cache
    # import os
    # APP_ROOT = os.path.dirname(os.path.abspath(__file__))
    # APP_ROOT = APP_ROOT[:-9]
    # if os.path.isfile('.cache'):
    #   os.remove(os.path.join(APP_ROOT, '.cache'))
    #   print(APP_ROOT)

    # Start Oauth2

    # auth_manager = SpotifyClientCredentials()
    # sp = spotipy.Spotify(auth_manager=auth_manager)

    # export SPOTIPY_CLIENT_ID='eae14429b373461aadc72104110154f9'
    # export SPOTIPY_CLIENT_SECRET='ada7bc6d1a1d4eada84cf382ae26c4f0'

    # username = '******'
    scope = "user-read-recently-played playlist-modify-public user-library-modify playlist-read-collaborative playlist-modify-private"
    redirect_uri = "https://www.roomy-pennapps.space/home/"
    # redirect_uri = "http://localhost:8080/"
    # redirect_uri = "https://papps2020.uc.r.appspot.com/user/callback/"
    # redirect_uri = "http://example.com/callback/"

    # username = '******'
    # token = util.prompt_for_user_token(username, scope, client_id ="eae14429b373461aadc72104110154f9", client_secret = "ada7bc6d1a1d4eada84cf382ae26c4f0", redirect_uri='https://www.roomy-pennapps.space/home/')
    token = True
    if token:

        sp_auth = SpotifyOAuth(
            client_id="eae14429b373461aadc72104110154f9",
            client_secret="ada7bc6d1a1d4eada84cf382ae26c4f0",
            redirect_uri=redirect_uri,
            scope=scope)
        sp = spotipy.Spotify(auth_manager=sp_auth)

        # sp = spotipy.Spotify(auth=token)

        # url = sp_auth.get_authorize_url()
        # print(url)

    else:
        # print("Can't get token for ", username)
        print("Error getting token")

    # # Get recently played song from the user, and get the artist name and artist id

    results = sp.current_user_recently_played()
    # print(results)
    print(sp.current_user())

    for idx, item in enumerate(results['items']):
        track = item['track']
        artist_id = track['artists'][0]['id']
        artist_name = track['artists'][0]['name']
        # pp.pprint(track)
        # print(artist_name, artist_id)
        break

    # now get artist info and extract genre

    resp = requests.get(
        'https://api.spotify.com/v1/artists/' + artist_id,
        headers={
            'Authorization':
            '{} {}'.format(sp.auth_manager.get_cached_token()['token_type'],
                           sp.auth_manager.get_cached_token()['access_token'])
        })
    if resp.status_code != 200:
        print("ERROR!")

    genres = resp.json()['genres']
    # print(genres)

    user.update({"genres": genres, "artist": artist_id})

    return custom_response({"result": "good"}, 200)
예제 #13
0
def add_cafe_playlist(username):
    user = UserModel.get_user_by_name(username)

    artist_id = user.artist
    genres = user.genres

    scope = "user-read-recently-played playlist-modify-public user-library-modify playlist-read-collaborative playlist-modify-private"
    redirect_uri = "https://www.roomy-pennapps.space/home/"
    # redirect_uri = "http://localhost:8080/"
    # redirect_uri = "https://papps2020.uc.r.appspot.com/user/callback/"
    # redirect_uri = "http://example.com/callback/"

    # username = '******'
    # token = util.prompt_for_user_token(username, scope, client_id ="eae14429b373461aadc72104110154f9", client_secret = "ada7bc6d1a1d4eada84cf382ae26c4f0", redirect_uri='https://www.roomy-pennapps.space/home/')
    token = True
    if token:

        sp_auth = SpotifyOAuth(
            client_id="eae14429b373461aadc72104110154f9",
            client_secret="ada7bc6d1a1d4eada84cf382ae26c4f0",
            redirect_uri=redirect_uri,
            scope=scope)
        sp = spotipy.Spotify(auth_manager=sp_auth)

        # sp = spotipy.Spotify(auth=token)

        # url = sp_auth.get_authorize_url()
        # print(url)

    else:
        # print("Can't get token for ", username)
        print("Error getting token")

    # artist_id, genres

    # Get random new songs from seeds (genre and artist)

    resp = requests.get(
        'https://api.spotify.com/v1/recommendations/?market={}&seed_artists={}&seed_genres={}&min_energy={}&min_popularity={}'
        .format('US', artist_id, ','.join(genres[:5]), 0.4, 50),
        headers={
            'Authorization':
            '{} {}'.format(sp.auth_manager.get_cached_token()['token_type'],
                           sp.auth_manager.get_cached_token()['access_token'])
        })
    if resp.status_code != 200:
        print("ERROR2")

    # pp.pprint(resp.json())
    # pp.pprint(resp.json()['tracks'])
    # pp.pprint(resp.json()['tracks'][0])
    # print(len(resp.json()['tracks']))

    uri = resp.json()['tracks'][0]['uri']
    # print(resp.json()['tracks'][0]['name'], resp.json()['tracks'][0]['artists'][0]['name'])

    # ADD NEW TRACK TO PLAYLIST

    sp_auth = SpotifyOAuth(client_id="eae14429b373461aadc72104110154f9",
                           client_secret="ada7bc6d1a1d4eada84cf382ae26c4f0",
                           redirect_uri=redirect_uri,
                           scope=scope,
                           cache_path='.shjangcache')
    sp = spotipy.Spotify(auth_manager=sp_auth)

    cafe_playlist_id = '2P8cx6O6JIu0sT2ItymYNI'
    # "https://open.spotify.com/embed/playlist/5sHebLj2M8wPPc1rfLKtX9?si=ulRKMYT9R8C7Scmcny3fJQ"

    sp.playlist_add_items(cafe_playlist_id, [uri])

    return custom_response({"result": "good"}, 200)
예제 #14
0
import requests
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from bs4 import BeautifulSoup

CLIENT_ID = "your_client_id"
CLIENT_SECRET = "your_client_secret"

auth_scope = "playlist-modify-private"

sp = spotipy.Spotify(
    auth_manager=SpotifyOAuth(client_id=CLIENT_ID,
                              client_secret=CLIENT_SECRET,
                              redirect_uri="https://example.com",
                              scope=auth_scope))

user_id = sp.current_user()["id"]

billboard_url = "https://www.billboard.com/charts/hot-100/"
date_input = input(
    "Which year do you want to travel to? Type the date in this format YYYY-MM-DD: "
)
year = date_input.split("-")[0]
response = requests.get(f"{billboard_url}{date_input}")
billboard_html = response.text
soup = BeautifulSoup(billboard_html, "html.parser")
songs = soup.select(".chart-element__information__song")
song_list = [song.text for song in songs]

songs_uri_list = []
for song in song_list:
예제 #15
0
import spotipy
from spotipy.oauth2 import SpotifyOAuth

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
    client_id="CLIENT_ID",
    client_secret="CLIENT_SECRET",
    redirect_uri="http://localhost:8001#",
    scope="user-library-read user-read-recently-played"))

results = sp.current_user_saved_tracks()
for idx, item in enumerate(results['items']):
    track = item['track']
    print(idx, track['artists'][0]['name'], " – ", track['name'])
예제 #16
0
파일: bot.py 프로젝트: davidjxu21/CollaBot
import spotipy
from dotenv import load_dotenv
from spotipy.oauth2 import SpotifyOAuth

load_dotenv()

#Discord Infomration
TOKEN = os.getenv('DISCORD_TOKEN')
CHANNEL = os.getenv('CHANNEL')

#Spotipy Information
SPOTIPY_CLIENT_ID = os.getenv('SPOTIPY_CLIENT_ID')
SPOTIPY_CLIENT_SECRET = os.getenv('SPOTIPY_CLIENT_SECRET')
SPOTIPY_REDIRECT_URI = os.getenv('SPOTIPY_REDIRECT_URI')

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope="playlist-modify-public"))
playlist = os.getenv('PLAYLIST')

client = discord.Client()


@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord')


@client.event
async def on_message(message):
    if message.author == client.user:
        return
예제 #17
0
# Grabs app's Spotify client ID & secret from my secrets.sh file
spotify_client_id = os.environ['SPOTIPY_CLIENT_ID']
spotify_client_secret = os.environ['SPOTIPY_CLIENT_SECRET']
spotify_redirect_uri = os.environ['SPOTIPY_REDIRECT_URI']

# The Spotify scope authorization for the user
spotify_scope = 'playlist-modify-public'

# Initialize Spotify Client Credentials object with app's client ID/secret
client_credentials = SpotifyClientCredentials(
    client_id=spotify_client_id, client_secret=spotify_client_secret)

spotify_oauth = SpotifyOAuth(client_id=spotify_client_id,
                             client_secret=spotify_client_secret,
                             redirect_uri=spotify_redirect_uri,
                             state=None,
                             scope=spotify_scope,
                             cache_path=None)


@app.route('/')
def index():
    """Homepage"""

    spotify_authorize_url = spotify_oauth.get_authorize_url()
    url = spotify_authorize_url + '&show_dialog=true'

    return render_template("home.html", url=url)


@app.route('/festivals')
예제 #18
0
import os

from spotipy.oauth2 import SpotifyClientCredentials
from spotipy.oauth2 import SpotifyOAuth
from math import pi, ceil
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn import svm

# spotify authentication: client_id, client_secret, username need real values
scope = "user-library-read playlist-modify-private playlist-modify-public"
OAuth = SpotifyOAuth(scope=scope,
                     redirect_uri='http://localhost:8889/callback',
                     client_id='id',
                     client_secret='secret',
                     username='******')

sp = spotipy.Spotify(auth_manager=OAuth)


def get_features_from_favourites():
    '''
    Returns a dataframe of the current user's favourite songs
    '''
    df_result = pd.DataFrame()
    track_list = ''
    added_ts_list = []
    artist_list = []
    title_list = []
예제 #19
0
spotifyClientId = config['spotify']['clientId']
spotifyClientSecret = config['spotify']['clientSecret']
spotifyRedirectUri = config['spotify']['redirectUri']
spotifyScope = config['spotify']['scope']
spotifyUsername = config['spotify']['username']

hueBridgeIp = config['hue']['bridgeIp']

hueBridge = Bridge(hueBridgeIp)
hueBridge.connect()

spotify = spotipy.Spotify(
    auth_manager=SpotifyOAuth(client_id=spotifyClientId,
                              client_secret=spotifyClientSecret,
                              redirect_uri=spotifyRedirectUri,
                              scope=spotifyScope,
                              open_browser=False,
                              username=spotifyUsername))

deviceList = spotify.devices()['devices']
hueGroups = hueBridge.groups

print("Your Hue groups are:")

for group in hueGroups:
    print(group.name)

print()

print("Your Spotify devices are:")
예제 #20
0
# Shows a user's playlists

import spotipy
from spotipy.oauth2 import SpotifyOAuth

scope = 'playlist-read-private'
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

results = sp.current_user_playlists(limit=50)
for i, item in enumerate(results['items']):
    print("%d %s" % (i, item['name']))
예제 #21
0
 def login(self) -> spotipy.Spotify:
     return spotipy.Spotify(oauth_manager=SpotifyOAuth(client_id=secrets.clientID, client_secret=secrets.clientSecret,
                            redirect_uri=self.CLIENT_REDIRECT, scope=self.SCOPE, username=self.username,
                            show_dialog=True))
예제 #22
0
from spotipy.oauth2 import SpotifyClientCredentials
from spotipy.oauth2 import SpotifyOAuth
from pprint import pprint

MAX_LIMIT = 50

# get the default config from configuration file
app_config = configparser.ConfigParser()
app_config.read('app_credentials.conf')
default_config = app_config['default']

scope = 'user-library-read'  # I guess we might also need user-read-private or even user-read-email for visual identification on web

auth_manager = SpotifyOAuth(client_id=default_config['client_id'],
                            client_secret=default_config['client_secret'],
                            redirect_uri='http://localhost:8888/callback/',
                            scope=scope,
                            open_browser=True)

sp = spotipy.Spotify(auth_manager=auth_manager)


def get_all_current_user_saved_tracks():
    def add_track(track_info):
        artists = track_info['track']['artists']
        artists_names = {artist['name'] for artist in artists}
        track_name = track_info['track']['name']

        if track_name in current_user_tracks:
            if artists_names not in current_user_tracks[
                    track_name]:  # to avoid duplicate lists of artists
예제 #23
0
            break
    for i in range(len(playlist)):
        for track in playlist[i]:
            playlist_features['artist'] = track['track']['album']['artists'][
                0]['name']
            playlist_features['album'] = track['track']['album']['name']
            playlist_features['track_name'] = track['track']['name']
            playlist_features['track_id'] = track['track']['id']
            playlist_features['popularity'] = track['track']['popularity']
            # Get audio features
            audio_features = sp_client.audio_features(
                playlist_features['track_id'])[0]
            for feature in playlist_features_list[5:]:
                playlist_features[feature] = audio_features[feature]
            #concat the dfs
            track_df = pd.DataFrame(playlist_features, index=[0])
            playlist_df = pd.concat([playlist_df, track_df], ignore_index=True)
    return playlist_df


if __name__ == '__main__':
    discover = 'spotify:playlist:37i9dQZEVXcUNzDN8qIGmk'
    discover = input("Input the playlist id : ")
    user = '******'
    auth_manager = SpotifyClientCredentials()
    scope = 'playlist-read-private, user-library-read'
    sp_client = spotipy.Spotify(
        auth_manager=SpotifyOAuth(scope=scope, username='******'))
    discover_df = fetch_playlist_features(user, discover)
    op_csv = input("Name of the o/p csv: ")
    discover_df.to_csv('dataset/{}.csv'.format(op_csv), index=False)
예제 #24
0
import spotipy

from spotipy.oauth2 import SpotifyOAuth

# set open_browser=False to prevent Spotipy from attempting to open the default browser
spotify = spotipy.Spotify(auth_manager=SpotifyOAuth(open_browser=False))

print(spotify.me())
예제 #25
0
from spotipy.oauth2 import SpotifyOAuth

CLIENT_ID = '261f2c14d2c5448eb75ceecbcd86c63e'
CLIENT_SECRET = '66aba98cb3e341bcb5e16b95118de030'

date = input('Input a date (YYYY-MM-DD): ')
response = requests.get('https://www.billboard.com/charts/hot-100/' + date)

soup = BeautifulSoup(response.text, 'html.parser')
target = soup.find_all('span', class_='chart-element__information__song')
song_names = [song.getText() for song in target]

sp = spotipy.Spotify(
    auth_manager=SpotifyOAuth(scope='playlist-modify-private',
                              redirect_uri='http://example.com',
                              client_id=CLIENT_ID,
                              client_secret=CLIENT_SECRET,
                              show_dialog=True,
                              cache_path='token.txt'))
user_id = sp.current_user()['id']
# print(user_id)

song_uris = []
year = date.split('-')[0]

for song in song_names:
    result = sp.search(q=f'track:{song} year:{year}', type='track')
    print(result)
    try:
        uri = result['tracks']['items'][0]['uri']
        song_uris.append(uri)
    except IndexError:
예제 #26
0
import spotipy
from flask import Flask, request, session, redirect
import pandas as pd
from spotipy.oauth2 import SpotifyOAuth
# STEP 1: Get user authentication access
clientid = '2b90b67f37914c32ad094916156f44aa'
secretid = 'c50524d981934e4c9e1dd88bcc2efacf'
scope = 'playlist-read-private playlist-modify-private playlist-modify-public'
redir = 'http%3A%2F%2Flocalhost%2F~samuelellgass%2F'

myOAuth = SpotifyOAuth(client_id=clientid,
                       client_secret=secretid,
                       redirect_uri=redir,
                       scope=scope)

access = spotipy.Spotify(auth_manager=myOAuth)

# STEP 2: Get ALL user playlists (URL? URI?)
# Data comes in as deeply nested dictionary form

# STEP 3: Collect Data from every song in every playlist into a CSV file or other storage tool

# THEN OUTPUT num_playlist tables of data for module 2 to process using data pipeline
예제 #27
0
def main():
    args = get_args()
    sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

    sp.current_user_saved_tracks_add(tracks=args.tids)
예제 #28
0

# Setup Spotify API Side

# If you need help with these, visit https://developer.spotify.com/documentation/web-api/
CLIENT_ID = "CHANGE THIS" # Your client_id from spotify app
CLIENT_SECRET = "CHANGE THIS" # Your client_secret from spotify app

OAUTH_AUTHORIZE_URL = 'https://accounts.spotify.com/authorize'
OAUTH_TOKEN_URL = 'https://accounts.spotify.com/api/token'
REDIRECT_URI = 'CHANGE THIS' # Your redirect uri from spotify app

scope = "user-read-playback-state"
username = "******" # Your spotify username

auth_manager = SpotifyOAuth(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri = REDIRECT_URI, username=username, scope=scope)
client_credentials_manager = SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager, auth_manager=auth_manager)


# Genius
# To get an API token, visit https://genius.com/api-clients and log in/sign up
GENIUS_API_TOKEN = "CHANGE THIS"
genius = lyricsgenius.Genius(GENIUS_API_TOKEN)



class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
예제 #29
0
def create_spotify_oauth():
    return SpotifyOAuth(client_id="616278c94375429084e241be7cef4949",
                        client_secret='dbe93ff256e74afb83bceeb59f33fb4b',
                        redirect_uri=url_for('is_user_authorised',
                                             _external=True),
                        scope="user-library-read")
예제 #30
0
# Scraping Billboard 100
# date = input("Which year do you want to travel to? Type the date in this format YYYY-MM-DD: ")
# response = requests.get("https://www.billboard.com/charts/hot-100/" + date)
date="2008-08-25"
response = requests.get("https://www.billboard.com/charts/hot-100/2008-08-25")
soup = BeautifulSoup(response.text, 'html.parser')
song_names_spans = soup.find_all("span", class_="chart-element__information__song")
song_names = [song.getText() for song in song_names_spans]

#Spotify Authentication
sp = spotipy.Spotify(
    auth_manager=SpotifyOAuth(
        scope="playlist-modify-private",
        redirect_uri="http://example.com",
        client_id="",
        client_secret=",
        show_dialog=True,
        cache_path="token.txt"
    )
)
user_id = sp.current_user()["id"]
print(user_id)

#Searching Spotify for songs by title
song_uris = []
year = date.split("-")[0]
for song in song_names:
    result = sp.search(q=f"track:{song} year:{year}", type="track")
    print(result)
    try:
        uri = result["tracks"]["items"][0]["uri"]
예제 #31
0
import random
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
from spotipy.oauth2 import SpotifyOAuth
from datetime import datetime
from statistics import mean
from statistics import stdev

# This class needs your Spotify client ID and client secret, as well as your
# user's id. (Instructions can be found on the Spotify for Developers site.)
client_id = ""
client_secret = ""
scope = "playlist-modify-private"
user = ""
spotify = spotipy.Spotify(auth_manager=SpotifyOAuth(
    client_id, client_secret, "http://localhost:8080", scope=scope))


class Explore:
    '''Allows exploration of related songs, artists, and albums on Spotify.
    Allows for the creation of playlists using these features.
    '''
    def top_user_artists(self):
        '''Finds the user's top artists from the short-term past. Returns a
        list containing the URIs (unique Spotify IDs) of these artists. 
        '''
        # We have to create a new authentication with a scope that allows us
        # to read the user's top artists.
        spotify_user = spotipy.Spotify(
            auth_manager=SpotifyOAuth(client_id,
                                      client_secret,
예제 #32
0
                lambda: fade_to_next_image(fade_val - 0.05, previm, nextim))
        else:
            canvas.image = ImageTk.PhotoImage(nextim)
            canvas.create_image(0, 0, image=canvas.image, anchor='nw')

    root.after(FADE_INTERVAL, lambda: update(None, startim))
    root.mainloop()


scope = 'user-read-currently-playing'

if len(sys.argv) > 1:
    username = sys.argv[1]
else:
    print("Usage: %s username" % (sys.argv[0], ))
    sys.exit()

try:
    assert len(sys.argv) == 3
except:
    print(
        'specify a display mode in the command line arguments, e.g. %s %s solid'
        % (
            sys.argv[0],
            sys.argv[1],
        ))
    quit()
mode = sys.argv[2]
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope, username=username))
run(sp)
예제 #33
0
def _make_oauth(*args, **kwargs):
    return SpotifyOAuth("CLID", "CLISEC", "REDIR", "STATE", *args, **kwargs)
예제 #34
0
                    index_col=0,
                    squeeze=True,
                    header=None)

#spotify setup
client_id = setup['client_id']
client_secret = setup['client_secret']
device_name = setup['client_id']
redirect_uri = setup['redirect_uri']
scope = setup['scope']
username = setup['username']
mic = setup['mic']

auth_manager = SpotifyOAuth(client_id=client_id,
                            client_secret=client_secret,
                            redirect_uri=redirect_uri,
                            scope=scope,
                            username=username)
spotify = sp.Spotify(auth_manager=auth_manager)

devices = spotify.devices()
deviceID = None
for d in devices['devices']:
    d['name'] = d['name'].replace('’', '\'')
    if d['name'] == device_name:
        deviceID = d['id']
        break

SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']

dictionary = PyDictionary()
예제 #35
0
        "name": clientId,
        "secret": clientSecret
    }  # create dictionary with values
    with open(fileName, "w") as jsonFile:  # open file as json_file
        json.dump(secrets, jsonFile)  # save dictionary in file

# permissions the app needs
# user-library-read:        for getting what playlists the user has
# streaming:                for starting playback (some other playback needs to be started already manually)
# user-read-playback-state: for reading what song is currently playing
scope = "user-library-read streaming user-read-playback-state"

# create spotify object
# will open browser window for authentication
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope,
                                               client_id=clientId,
                                               client_secret=clientSecret,
                                               redirect_uri=redirectUri))

playlists = sp.current_user_playlists()  # get all playlists

# print all available playlists
print("Available Playlists:")
for playlist in playlists['items']:
    print(playlist['name'])

# get userinput on what playlist to play
playlistName = input("What playlist do you wanna play? ")
print("playing " + playlistName)

for playlist in playlists['items']:  # iterate over all available playlists
    if playlist['name'] == playlistName:  # check if name is equal to userInput