mirror of
https://github.com/spotipy-dev/spotipy.git
synced 2026-06-19 01:03:53 +00:00
Move examples to spotipy-dev/spotipy-examples, add as submodule
This commit is contained in:
parent
e37b1a8a55
commit
d319c6e09f
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
[submodule "examples"]
|
||||
path = examples
|
||||
url = git@github.com:spotipy-dev/spotipy-examples.git
|
||||
4
FAQ.md
4
FAQ.md
@ -6,7 +6,7 @@ spotipy can only return fields documented on the Spotify web API https://develop
|
||||
|
||||
### How to use spotipy in an API?
|
||||
|
||||
Check out [this example Flask app](examples/app.py)
|
||||
Check out [this example Flask app](https://github.com/spotipy-dev/spotipy-examples/tree/main/apps/flask_api)
|
||||
|
||||
### How can I store tokens in a database rather than on the filesystem?
|
||||
|
||||
@ -51,7 +51,7 @@ must be specified: `search("abba", market="DE")`.
|
||||
If you cannot open a browser, set `open_browser=False` when instantiating SpotifyOAuth or SpotifyPKCE. You will be
|
||||
prompted to open the authorization URI manually.
|
||||
|
||||
See the [headless auth example](examples/headless.py).
|
||||
See the [headless auth example](https://github.com/spotipy-dev/spotipy-examples/blob/main/scripts/headless.py).
|
||||
|
||||
### My application is not responding
|
||||
|
||||
|
||||
@ -254,8 +254,8 @@ artist's name::
|
||||
artist = items[0]
|
||||
print(artist['name'], artist['images'][0]['url'])
|
||||
|
||||
There are many more examples of how to use *Spotipy* in the `Examples
|
||||
Directory <https://github.com/plamere/spotipy/tree/master/examples>`_ on GitHub.
|
||||
There are many more examples of how to use *Spotipy* in the `spotipy-examples
|
||||
repository <https://github.com/spotipy-dev/spotipy-examples>`_ on GitHub.
|
||||
|
||||
API Reference
|
||||
==============
|
||||
|
||||
1
examples
Submodule
1
examples
Submodule
@ -0,0 +1 @@
|
||||
Subproject commit c610a79705ef4aa55e4d61572a012f77b6f7245d
|
||||
@ -1,27 +0,0 @@
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
logger = logging.getLogger('examples.add_a_saved_album')
|
||||
logging.basicConfig(level='DEBUG')
|
||||
|
||||
scope = 'user-library-modify'
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Creates a playlist for user')
|
||||
parser.add_argument('-a', '--aids', action='append',
|
||||
required=True, help='Album ids')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
sp.current_user_saved_albums_add(albums=args.aids)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,29 +0,0 @@
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'user-library-modify'
|
||||
|
||||
logger = logging.getLogger('examples.add_a_saved_track')
|
||||
logging.basicConfig(level='DEBUG')
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Add tracks to Your '
|
||||
'Collection of saved tracks')
|
||||
parser.add_argument('-t', '--tids', action='append',
|
||||
required=True, help='Track ids')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
|
||||
sp.current_user_saved_tracks_add(tracks=args.tids)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,29 +0,0 @@
|
||||
"""
|
||||
Add episodes to current user's library
|
||||
Usage: add_saved_episodes.py -e episode_id episode_id ...
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'user-library-modify'
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Add episodes to library')
|
||||
# Default args set to This American Life episodes 814 and 815
|
||||
parser.add_argument('-e', '--eids', nargs='+',
|
||||
default=['6rxg9Lpt2ywNHFea8LxEBO', '7q8or6oYYRFQFYlA0remoy'],
|
||||
help='Episode ids')
|
||||
return parser.parse_args()
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
print('Adding following episode ids to library: ' + str(args.eids))
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
sp.current_user_saved_episodes_add(episodes=args.eids)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,29 +0,0 @@
|
||||
"""
|
||||
Add shows to current user's library
|
||||
Usage: add_saved_shows.py -s show_id show_id ...
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'user-library-modify'
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Add shows to library')
|
||||
# Default args set to Radiolab and 99% invisible
|
||||
parser.add_argument('-s', '--sids', nargs='+',
|
||||
default=['2hmkzUtix0qTqvtpPcMzEL', '2VRS1IJCTn2Nlkg33ZVfkM'],
|
||||
help='Show ids')
|
||||
return parser.parse_args()
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
print('Adding following show ids to library: ' + str(args.sids))
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
sp.current_user_saved_shows_add(shows=args.sids)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,29 +0,0 @@
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
logger = logging.getLogger('examples.add_tracks_to_playlist')
|
||||
logging.basicConfig(level='DEBUG')
|
||||
scope = 'playlist-modify-public'
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Adds track to user playlist')
|
||||
parser.add_argument('-u', '--uris', action='append',
|
||||
required=True, help='Track ids')
|
||||
parser.add_argument('-p', '--playlist', required=True,
|
||||
help='Playlist to add track to')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
sp.playlist_add_items(args.playlist, args.uris)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
115
examples/app.py
115
examples/app.py
@ -1,115 +0,0 @@
|
||||
"""
|
||||
Prerequisites
|
||||
|
||||
pip3 install spotipy Flask Flask-Session
|
||||
|
||||
// from your [app settings](https://developer.spotify.com/dashboard/applications)
|
||||
export SPOTIPY_CLIENT_ID=client_id_here
|
||||
export SPOTIPY_CLIENT_SECRET=client_secret_here
|
||||
export SPOTIPY_REDIRECT_URI='http://127.0.0.1:8080' // must contain a port
|
||||
// SPOTIPY_REDIRECT_URI must be added to your [app settings](https://developer.spotify.com/dashboard/applications)
|
||||
OPTIONAL
|
||||
// in development environment for debug output
|
||||
export FLASK_ENV=development
|
||||
// so that you can invoke the app outside the file's directory include
|
||||
export FLASK_APP=/path/to/spotipy/examples/app.py
|
||||
|
||||
// on Windows, use `SET` instead of `export`
|
||||
|
||||
Run app.py
|
||||
|
||||
python3 app.py OR python3 -m flask run
|
||||
NOTE: If receiving "port already in use" error, try other ports: 5000, 8090, 8888, etc...
|
||||
(will need to be updated in your Spotify app and SPOTIPY_REDIRECT_URI variable)
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from flask import Flask, redirect, request, session
|
||||
from flask_session import Session
|
||||
|
||||
import spotipy
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['SECRET_KEY'] = os.urandom(64)
|
||||
app.config['SESSION_TYPE'] = 'filesystem'
|
||||
app.config['SESSION_FILE_DIR'] = './.flask_session/'
|
||||
Session(app)
|
||||
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
|
||||
cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
|
||||
auth_manager = spotipy.oauth2.SpotifyOAuth(scope='user-read-currently-playing playlist-modify-private',
|
||||
cache_handler=cache_handler,
|
||||
show_dialog=True)
|
||||
|
||||
if request.args.get("code"):
|
||||
# Step 2. Being redirected from Spotify auth page
|
||||
auth_manager.get_access_token(request.args.get("code"))
|
||||
return redirect('/')
|
||||
|
||||
if not auth_manager.validate_token(cache_handler.get_cached_token()):
|
||||
# Step 1. Display sign in link when no token
|
||||
auth_url = auth_manager.get_authorize_url()
|
||||
return f'<h2><a href="{auth_url}">Sign in</a></h2>'
|
||||
|
||||
# Step 3. Signed in, display data
|
||||
spotify = spotipy.Spotify(auth_manager=auth_manager)
|
||||
return f'<h2>Hi {spotify.me()["display_name"]}, ' \
|
||||
f'<small><a href="/sign_out">[sign out]<a/></small></h2>' \
|
||||
f'<a href="/playlists">my playlists</a> | ' \
|
||||
f'<a href="/currently_playing">currently playing</a> | ' \
|
||||
f'<a href="/current_user">me</a>' \
|
||||
|
||||
|
||||
|
||||
@app.route('/sign_out')
|
||||
def sign_out():
|
||||
session.pop("token_info", None)
|
||||
return redirect('/')
|
||||
|
||||
|
||||
@app.route('/playlists')
|
||||
def playlists():
|
||||
cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
|
||||
auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
|
||||
if not auth_manager.validate_token(cache_handler.get_cached_token()):
|
||||
return redirect('/')
|
||||
|
||||
spotify = spotipy.Spotify(auth_manager=auth_manager)
|
||||
return spotify.current_user_playlists()
|
||||
|
||||
|
||||
@app.route('/currently_playing')
|
||||
def currently_playing():
|
||||
cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
|
||||
auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
|
||||
if not auth_manager.validate_token(cache_handler.get_cached_token()):
|
||||
return redirect('/')
|
||||
spotify = spotipy.Spotify(auth_manager=auth_manager)
|
||||
track = spotify.current_user_playing_track()
|
||||
if not track is None:
|
||||
return track
|
||||
return "No track currently playing."
|
||||
|
||||
|
||||
@app.route('/current_user')
|
||||
def current_user():
|
||||
cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
|
||||
auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
|
||||
if not auth_manager.validate_token(cache_handler.get_cached_token()):
|
||||
return redirect('/')
|
||||
spotify = spotipy.Spotify(auth_manager=auth_manager)
|
||||
return spotify.current_user()
|
||||
|
||||
|
||||
'''
|
||||
Following lines allow application to be run more conveniently with
|
||||
`python app.py` (Make sure you're using python3)
|
||||
(Also includes directive to leverage pythons threading capacity.)
|
||||
'''
|
||||
if __name__ == '__main__':
|
||||
app.run(threaded=True, port=int(os.environ.get("PORT",
|
||||
os.environ.get("SPOTIPY_REDIRECT_URI", 8080).split(":")[-1])))
|
||||
@ -1,52 +0,0 @@
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
logger = logging.getLogger('examples.artist_albums')
|
||||
logging.basicConfig(level='INFO')
|
||||
|
||||
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Gets albums from artist')
|
||||
parser.add_argument('-a', '--artist', required=True,
|
||||
help='Name of Artist')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def get_artist(name):
|
||||
results = sp.search(q='artist:' + name, type='artist')
|
||||
items = results['artists']['items']
|
||||
return items[0] if items else None
|
||||
|
||||
|
||||
def show_artist_albums(artist):
|
||||
albums = []
|
||||
results = sp.artist_albums(artist['id'], album_type='album')
|
||||
albums.extend(results['items'])
|
||||
while results['next']:
|
||||
results = sp.next(results)
|
||||
albums.extend(results['items'])
|
||||
seen = set() # to avoid dups
|
||||
albums.sort(key=lambda album: album['name'].lower())
|
||||
for album in albums:
|
||||
name = album['name']
|
||||
if name not in seen:
|
||||
logger.info(f'ALBUM: {name}')
|
||||
seen.add(name)
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
artist = get_artist(args.artist)
|
||||
if artist:
|
||||
show_artist_albums(artist)
|
||||
else:
|
||||
logger.error(f"Can't find artist: {artist}")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,71 +0,0 @@
|
||||
# Shows the list of all songs sung by the artist or the band
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
logger = logging.getLogger('examples.artist_discography')
|
||||
logging.basicConfig(level='INFO')
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Shows albums and tracks for '
|
||||
'given artist')
|
||||
parser.add_argument('-a', '--artist', required=True,
|
||||
help='Name of Artist')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def get_artist(name):
|
||||
results = sp.search(q='artist:' + name, type='artist')
|
||||
items = results['artists']['items']
|
||||
return items[0] if items else None
|
||||
|
||||
|
||||
def show_album_tracks(album):
|
||||
tracks = []
|
||||
results = sp.album_tracks(album['id'])
|
||||
tracks.extend(results['items'])
|
||||
while results['next']:
|
||||
results = sp.next(results)
|
||||
tracks.extend(results['items'])
|
||||
for i, track in enumerate(tracks):
|
||||
logger.info(f'{i + 1}. {track["name"]}')
|
||||
|
||||
|
||||
def show_artist_albums(artist):
|
||||
albums = []
|
||||
results = sp.artist_albums(artist['id'], album_type='album')
|
||||
albums.extend(results['items'])
|
||||
while results['next']:
|
||||
results = sp.next(results)
|
||||
albums.extend(results['items'])
|
||||
logger.info(f'Total albums: {len(albums)}')
|
||||
unique = set() # skip duplicate albums
|
||||
for album in albums:
|
||||
name = album['name'].lower()
|
||||
if name not in unique:
|
||||
logger.info(f'ALBUM: {name}')
|
||||
unique.add(name)
|
||||
show_album_tracks(album)
|
||||
|
||||
|
||||
def show_artist(artist):
|
||||
logger.info(f'===={artist["name"]}====')
|
||||
logger.info(f'Popularity: {artist["popularity"]}')
|
||||
if len(artist['genres']) > 0:
|
||||
logger.info(f"Genres: {', '.join(artist['genres'])}")
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
artist = get_artist(args.artist)
|
||||
show_artist(artist)
|
||||
show_artist_albums(artist)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
main()
|
||||
@ -1,43 +0,0 @@
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
logger = logging.getLogger('examples.artist_recommendations')
|
||||
logging.basicConfig(level='INFO')
|
||||
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Recommendations for the '
|
||||
'given artist')
|
||||
parser.add_argument('-a', '--artist', required=True, help='Name of Artist')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def get_artist(name):
|
||||
results = sp.search(q='artist:' + name, type='artist')
|
||||
items = results['artists']['items']
|
||||
return items[0] if items else None
|
||||
|
||||
|
||||
def show_recommendations_for_artist(artist):
|
||||
results = sp.recommendations(seed_artists=[artist['id']])
|
||||
for track in results['tracks']:
|
||||
logger.info(f'Recommendation: {track["name"]} - {track["artists"][0]["name"]}')
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
artist = get_artist(args.artist)
|
||||
if artist:
|
||||
show_recommendations_for_artist(artist)
|
||||
else:
|
||||
logger.error("Can't find that artist", args.artist)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,22 +0,0 @@
|
||||
# shows audio analysis for the given track
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
tid = sys.argv[1]
|
||||
else:
|
||||
tid = 'spotify:track:4TTV7EcfroSLWzXRY6gLv6'
|
||||
|
||||
start = time.time()
|
||||
analysis = sp.audio_analysis(tid)
|
||||
delta = time.time() - start
|
||||
print(json.dumps(analysis, indent=4))
|
||||
print(f"analysis retrieved in {delta:.2f} seconds")
|
||||
@ -1,34 +0,0 @@
|
||||
# shows acoustic features for tracks for the given artist
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
sp.trace = False
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
artist_name = ' '.join(sys.argv[1:])
|
||||
else:
|
||||
artist_name = 'weezer'
|
||||
|
||||
results = sp.search(q=artist_name, limit=50)
|
||||
tids = []
|
||||
for i, t in enumerate(results['tracks']['items']):
|
||||
print(' ', i, t['name'])
|
||||
tids.append(t['uri'])
|
||||
|
||||
start = time.time()
|
||||
features = sp.audio_features(tids)
|
||||
delta = time.time() - start
|
||||
for feature in features:
|
||||
print(json.dumps(feature, indent=4))
|
||||
print()
|
||||
analysis = sp._get(feature['analysis_url'])
|
||||
print(json.dumps(analysis, indent=4))
|
||||
print()
|
||||
print(f"features retrieved in {delta:.2f} seconds")
|
||||
@ -1,33 +0,0 @@
|
||||
import matplotlib.pyplot as plt
|
||||
# Import the extra necessary libraries for this example
|
||||
# These libraries are not included in the default packages
|
||||
import pandas as pd
|
||||
import seaborn as sns
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
# Set up Spotify credentials
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
|
||||
# Fetch audio features of tracks from any playlist
|
||||
playlist_id = '37i9dQZEVXbMDoHDwVN2tF'
|
||||
results = sp.playlist_tracks(playlist_id)
|
||||
tracks = results['items']
|
||||
track_ids = [track['track']['id'] for track in tracks]
|
||||
audio_features = sp.audio_features(track_ids)
|
||||
|
||||
# Create a DataFrame of audio features
|
||||
df = pd.DataFrame(audio_features)
|
||||
df = df[['danceability', 'energy', 'speechiness', 'acousticness',
|
||||
'instrumentalness', 'liveness', 'valence', 'tempo']]
|
||||
|
||||
# Generate a correlation matrix
|
||||
correlation_matrix = df.corr()
|
||||
|
||||
# Plot the correlation matrix using seaborn
|
||||
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm')
|
||||
|
||||
# Show the plot
|
||||
plt.show()
|
||||
@ -1,22 +0,0 @@
|
||||
# shows acoustic features for tracks for the given artist
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
sp.trace = True
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
tids = sys.argv[1:]
|
||||
print(tids)
|
||||
|
||||
start = time.time()
|
||||
features = sp.audio_features(tids)
|
||||
delta = time.time() - start
|
||||
print(json.dumps(features, indent=4))
|
||||
print(f"features retrieved in {delta:.2f} seconds")
|
||||
@ -1,47 +0,0 @@
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
logger = logging.getLogger('examples.change_playlist_details')
|
||||
logging.basicConfig(level='DEBUG')
|
||||
|
||||
scope = 'playlist-modify-public playlist-modify-private'
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Modify details of playlist')
|
||||
parser.add_argument('-p', '--playlist', required=True,
|
||||
help='Playlist id to alter details')
|
||||
parser.add_argument('-n', '--name', required=False,
|
||||
help='Name of playlist')
|
||||
parser.add_argument('--public', action='store_true', required=False,
|
||||
help='Include param if playlist is public')
|
||||
parser.add_argument('--private', action='store_false', required=False,
|
||||
default=None,
|
||||
help='Include param to make playlist is private')
|
||||
parser.add_argument('-c', '--collaborative', action='store_true',
|
||||
required=False, default=None,
|
||||
help='Include param if playlist is collaborative')
|
||||
parser.add_argument('-i', '--independent', action='store_false',
|
||||
required=False, default=None,
|
||||
help='Include param to make playlist non collaborative')
|
||||
parser.add_argument('-d', '--description', default=None, required=False,
|
||||
help='Description of playlist')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
sp.playlist_change_details(
|
||||
args.playlist,
|
||||
name=args.name,
|
||||
public=args.public or args.private,
|
||||
collaborative=args.collaborative or args.independent,
|
||||
description=args.description)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,32 +0,0 @@
|
||||
"""
|
||||
Check if shows are saved in user's library
|
||||
Usage: check_show_is_saved -s show_id show_id ...
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'user-library-read'
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Check that a show is saved')
|
||||
# Default args set to Radiolab and 99% invisible
|
||||
parser.add_argument('-s', '--sids', nargs='+',
|
||||
default=['2hmkzUtix0qTqvtpPcMzEL', '2VRS1IJCTn2Nlkg33ZVfkM'],
|
||||
help='Show ids')
|
||||
return parser.parse_args()
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
results = sp.current_user_saved_episodes_contains(episodes=args.sids)
|
||||
show_names = sp.shows(shows=args.sids)
|
||||
# Print show names and if show is saved by current user
|
||||
for i, show in enumerate(show_names['shows']):
|
||||
print(show['name'] + ': ' + str(results[i]))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,11 +0,0 @@
|
||||
from pprint import pprint
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
|
||||
search_str = 'Muse'
|
||||
result = sp.search(search_str)
|
||||
pprint(result)
|
||||
@ -1,19 +0,0 @@
|
||||
# Prints whether a track exists in your collection of saved tracks
|
||||
|
||||
import pprint
|
||||
import sys
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'user-library-read'
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
tid = sys.argv[1]
|
||||
else:
|
||||
print(f"Usage: {sys.argv[0]} track-id ...")
|
||||
sys.exit()
|
||||
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
results = sp.current_user_saved_tracks_contains(tracks=[tid])
|
||||
pprint.pprint(results)
|
||||
@ -1,31 +0,0 @@
|
||||
# Creates a playlist for a user
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
logger = logging.getLogger('examples.create_playlist')
|
||||
logging.basicConfig(level='DEBUG')
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Creates a playlist for user')
|
||||
parser.add_argument('-p', '--playlist', required=True,
|
||||
help='Name of Playlist')
|
||||
parser.add_argument('-d', '--description', required=False, default='',
|
||||
help='Description of Playlist')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
scope = "playlist-modify-public"
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
user_id = sp.me()['id']
|
||||
sp.user_playlist_create(user_id, args.playlist, description=args.description)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,19 +0,0 @@
|
||||
# Delete a track from 'Your Collection' of saved tracks
|
||||
|
||||
import pprint
|
||||
import sys
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'user-library-modify'
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
tid = sys.argv[1]
|
||||
else:
|
||||
print(f"Usage: {sys.argv[0]} track-id ...")
|
||||
sys.exit()
|
||||
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
results = sp.current_user_saved_tracks_delete(tracks=[tid])
|
||||
pprint.pprint(results)
|
||||
@ -1,29 +0,0 @@
|
||||
"""
|
||||
Delete episodes from current user's library
|
||||
Usage: delete_saved_episodes.py -e episode_id episode_id ...
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'user-library-modify'
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Delete episodes from library')
|
||||
# Default args set to This American Life episodes 814 and 815
|
||||
parser.add_argument('-e', '--eids', nargs='+',
|
||||
default=['6rxg9Lpt2ywNHFea8LxEBO', '7q8or6oYYRFQFYlA0remoy'],
|
||||
help='Episode ids')
|
||||
return parser.parse_args()
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
print('Deleting following episode ids from library: ' + str(args.eids))
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
sp.current_user_saved_episodes_delete(episodes=args.eids)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,25 +0,0 @@
|
||||
# Follow a playlist
|
||||
|
||||
import argparse
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'playlist-modify-public'
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Follows a playlist based on playlist ID')
|
||||
# Default to Top 50 Global if no playlist is provided
|
||||
parser.add_argument('-p', '--playlist', help='Playlist ID', nargs='?', default='37i9dQZEVXbMDoHDwVN2tF')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
# Uses Lofi Girl playlist
|
||||
playlist = args.playlist or '0vvXsWCC9xrXsKd4FyS8kM'
|
||||
spotipy.Spotify(auth_manager=SpotifyOAuth()).current_user_follow_playlist(playlist)
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,30 +0,0 @@
|
||||
"""
|
||||
Print chapter titles and lengths for given audiobook
|
||||
Usage: get_audiobooks_chapters_info.py -a audiobook_id
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Get chapter info for an audiobook')
|
||||
# Default set to Dune
|
||||
parser.add_argument('-a', '--audiobook', default='2h01INWMBvfpzNMpGFzhdF', help='Audiobook id')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
print('Getting chapter info for follow audiobook id: ' + str(args.audiobook))
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth())
|
||||
results = sp.get_audiobook_chapters(id=args.audiobook)
|
||||
# Print chapter name and length
|
||||
for item in results['items']:
|
||||
print('Name: ' + item['name'] + ', length: ' + str(round(item['duration_ms']/60000,1)) + ' minutes')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,31 +0,0 @@
|
||||
"""
|
||||
Print audiobook title and description for a list of audiobook ids
|
||||
Usage: get_audiobooks_info.py -a audiobook_id audiobook_id ...
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Get information for a list of audiobooks')
|
||||
# Defaults set to The Great Gatsby, The Chronicles of Narnia and Dune
|
||||
parser.add_argument('-a', '--aids', nargs='+',
|
||||
default=['6qjpt1CUHhKXiNoeNoU7nu', '1ezmXd68LbDtxebvygEQ2U', '2h01INWMBvfpzNMpGFzhdF'],
|
||||
help='Audiobook ids')
|
||||
return parser.parse_args()
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
print('Getting info for follow audiobook ids: ' + str(args.aids) + '\n')
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth())
|
||||
results = sp.get_audiobooks(ids=args.aids)
|
||||
# Print book title and description
|
||||
for book in results['audiobooks']:
|
||||
print('Title: ' + book['name'] + '\n' + book['description'] + '\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,7 +0,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())
|
||||
@ -1,10 +0,0 @@
|
||||
from pprint import pprint
|
||||
|
||||
import spotipy
|
||||
import spotipy.util as util
|
||||
|
||||
while True:
|
||||
username = input("Type the Spotify user ID to use: ")
|
||||
token = util.prompt_for_user_token(username, show_dialog=True)
|
||||
sp = spotipy.Spotify(token)
|
||||
pprint(sp.me())
|
||||
@ -1,11 +0,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(f"{i} {item['name']}")
|
||||
@ -1,17 +0,0 @@
|
||||
# Shows the top artists for a user
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'user-top-read'
|
||||
ranges = ['short_term', 'medium_term', 'long_term']
|
||||
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
|
||||
for sp_range in ['short_term', 'medium_term', 'long_term']:
|
||||
print("range:", sp_range)
|
||||
|
||||
results = sp.current_user_top_artists(time_range=sp_range, limit=50)
|
||||
|
||||
for i, item in enumerate(results['items']):
|
||||
print(i, item['name'])
|
||||
print()
|
||||
@ -1,16 +0,0 @@
|
||||
# Shows the top tracks for a user
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'user-top-read'
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
|
||||
ranges = ['short_term', 'medium_term', 'long_term']
|
||||
|
||||
for sp_range in ranges:
|
||||
print("range:", sp_range)
|
||||
results = sp.current_user_top_tracks(time_range=sp_range, limit=50)
|
||||
for i, item in enumerate(results['items']):
|
||||
print(i, item['name'], '//', item['artists'][0]['name'])
|
||||
print()
|
||||
@ -1,53 +0,0 @@
|
||||
# Import the extra necessary libraries for this example
|
||||
# These libraries are not included in the default packages
|
||||
import pandas as pd
|
||||
from sklearn.cluster import KMeans
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
# Set up Spotify credentials
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
|
||||
client_id="YOUR_APP_CLIENT_ID",
|
||||
client_secret="YOUR_APP_CLIENT_SECRET",
|
||||
redirect_uri="YOUR_APP_REDIRECT_URI",
|
||||
scope="playlist-modify-private,user-library-read"))
|
||||
|
||||
|
||||
# get the user's username
|
||||
username = sp.me()['id']
|
||||
|
||||
# Get the user's liked tracks
|
||||
saved_tracks = sp.current_user_saved_tracks(limit=50)['items']
|
||||
|
||||
# Extract audio features for liked tracks
|
||||
track_ids = []
|
||||
audio_features = []
|
||||
for track in saved_tracks:
|
||||
track_ids.append(track['track']['id'])
|
||||
audio_features.append(sp.audio_features(track['track']['id'])[0])
|
||||
|
||||
# Create a DataFrame from the audio features
|
||||
df = pd.DataFrame(audio_features)
|
||||
|
||||
# Perform clustering on some audio features
|
||||
features = df[['danceability', 'energy', 'valence', 'acousticness']]
|
||||
kmeans = KMeans(n_clusters=5, random_state=42, n_init=10)
|
||||
df['cluster'] = kmeans.fit_predict(features)
|
||||
|
||||
# Select a representative track from each cluster
|
||||
representative_tracks = []
|
||||
for cluster in range(5):
|
||||
cluster_tracks = df[df['cluster'] == cluster]
|
||||
representative_track = cluster_tracks.iloc[0]['id']
|
||||
representative_tracks.append(representative_track)
|
||||
|
||||
# Create a playlist with the representative tracks
|
||||
playlist = sp.user_playlist_create(
|
||||
user=username, name='Personalized Playlist', public=False)
|
||||
sp.playlist_add_items(
|
||||
playlist_id=playlist['id'], items=representative_tracks)
|
||||
|
||||
# Print the URL of the created playlist
|
||||
print("Playlist created successfully. You can access it at:",
|
||||
playlist['external_urls']['spotify'])
|
||||
@ -1,22 +0,0 @@
|
||||
from pprint import pprint
|
||||
from time import sleep
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = "user-read-playback-state,user-modify-playback-state"
|
||||
sp = spotipy.Spotify(client_credentials_manager=SpotifyOAuth(scope=scope))
|
||||
|
||||
# Shows playing devices
|
||||
res = sp.devices()
|
||||
pprint(res)
|
||||
|
||||
# Change track
|
||||
sp.start_playback(uris=['spotify:track:6gdLoMygLsgktydTQ71b15'])
|
||||
|
||||
# Change volume
|
||||
sp.volume(100)
|
||||
sleep(2)
|
||||
sp.volume(50)
|
||||
sleep(2)
|
||||
sp.volume(100)
|
||||
@ -1,30 +0,0 @@
|
||||
# get all non-local tracks of a playlist
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
# playlist id of global top 50
|
||||
PlaylistExample = '37i9dQZEVXbMDoHDwVN2tF'
|
||||
|
||||
# create spotipy client
|
||||
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
|
||||
|
||||
# load the first 100 songs
|
||||
tracks = []
|
||||
result = sp.playlist_items(PlaylistExample, additional_types=['track'])
|
||||
tracks.extend(result['items'])
|
||||
|
||||
# if playlist is larger than 100 songs, continue loading it until end
|
||||
while result['next']:
|
||||
result = sp.next(result)
|
||||
tracks.extend(result['items'])
|
||||
|
||||
# remove all local songs
|
||||
i = 0 # just for counting how many tracks are local
|
||||
for item in tracks:
|
||||
if item['is_local']:
|
||||
tracks.remove(item)
|
||||
i += 1
|
||||
|
||||
|
||||
# print result
|
||||
print("Playlist length: " + str(len(tracks)) + "\nExcluding: " + str(i))
|
||||
@ -1,22 +0,0 @@
|
||||
from pprint import pprint
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
|
||||
|
||||
pl_id = 'spotify:playlist:5RIbzhG2QqdkaP24iXLnZX'
|
||||
offset = 0
|
||||
|
||||
while True:
|
||||
response = sp.playlist_items(pl_id,
|
||||
offset=offset,
|
||||
fields='items.track.id,total',
|
||||
additional_types=['track'])
|
||||
|
||||
if len(response['items']) == 0:
|
||||
break
|
||||
|
||||
pprint(response['items'])
|
||||
offset = offset + len(response['items'])
|
||||
print(offset, "/", response['total'])
|
||||
@ -1,11 +0,0 @@
|
||||
import json
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
|
||||
playlist_id = '37i9dQZEVXbJiZcmkrIHGU'
|
||||
results = sp.playlist(playlist_id)
|
||||
print(json.dumps(results, indent=4))
|
||||
@ -1,26 +0,0 @@
|
||||
# Removes tracks from a playlist
|
||||
|
||||
import pprint
|
||||
import sys
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
if len(sys.argv) > 2:
|
||||
playlist_id = sys.argv[1]
|
||||
track_ids_and_positions = sys.argv[2:]
|
||||
track_ids = []
|
||||
for t_pos in sys.argv[2:]:
|
||||
tid, pos = t_pos.split(',')
|
||||
track_ids.append({"uri": tid, "positions": [int(pos)]})
|
||||
else:
|
||||
print(
|
||||
f"Usage: {sys.argv[0]} playlist_id track_id,pos track_id,pos ...")
|
||||
sys.exit()
|
||||
|
||||
scope = 'playlist-modify-public'
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
|
||||
results = sp.playlist_remove_specific_occurrences_of_items(
|
||||
playlist_id, track_ids)
|
||||
pprint.pprint(results)
|
||||
@ -1,21 +0,0 @@
|
||||
# Removes tracks from playlist
|
||||
import pprint
|
||||
import sys
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
if len(sys.argv) > 2:
|
||||
playlist_id = sys.argv[1]
|
||||
track_ids = sys.argv[2:]
|
||||
else:
|
||||
print(f"Usage: {sys.argv[0]} playlist_id track_id ...")
|
||||
sys.exit()
|
||||
|
||||
scope = 'playlist-modify-public'
|
||||
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
|
||||
results = sp.playlist_remove_all_occurrences_of_items(
|
||||
playlist_id, track_ids)
|
||||
pprint.pprint(results)
|
||||
@ -1,21 +0,0 @@
|
||||
# Replaces all tracks in a playlist
|
||||
|
||||
import pprint
|
||||
import sys
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
if len(sys.argv) > 2:
|
||||
playlist_id = sys.argv[1]
|
||||
track_ids = sys.argv[2:]
|
||||
else:
|
||||
print(f"Usage: {sys.argv[0]} playlist_id track_id ...")
|
||||
sys.exit()
|
||||
|
||||
scope = 'playlist-modify-public'
|
||||
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
|
||||
results = sp.playlist_replace_items(playlist_id, track_ids)
|
||||
pprint.pprint(results)
|
||||
@ -1,16 +0,0 @@
|
||||
# shows artist info for a URN or URL
|
||||
|
||||
import pprint
|
||||
import sys
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
search_str = sys.argv[1]
|
||||
else:
|
||||
search_str = 'Radiohead'
|
||||
|
||||
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
|
||||
result = sp.search(search_str)
|
||||
pprint.pprint(result)
|
||||
@ -1,16 +0,0 @@
|
||||
# shows album info for a URN or URL
|
||||
|
||||
import sys
|
||||
from pprint import pprint
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
urn = sys.argv[1]
|
||||
else:
|
||||
urn = 'spotify:album:5yTx83u3qerZF7GRJu7eFk'
|
||||
|
||||
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
|
||||
album = sp.album(urn)
|
||||
pprint(album)
|
||||
@ -1,17 +0,0 @@
|
||||
# shows artist info for a URN or URL
|
||||
|
||||
import sys
|
||||
from pprint import pprint
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
urn = sys.argv[1]
|
||||
else:
|
||||
urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu'
|
||||
|
||||
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
|
||||
|
||||
artist = sp.artist(urn)
|
||||
pprint(artist)
|
||||
@ -1,18 +0,0 @@
|
||||
# shows artist info for a URN or URL
|
||||
# scope is not required for this function
|
||||
|
||||
import sys
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
urn = sys.argv[1]
|
||||
else:
|
||||
urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu'
|
||||
|
||||
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
|
||||
response = sp.artist_top_tracks(urn)
|
||||
|
||||
for track in response['tracks']:
|
||||
print(track['name'])
|
||||
@ -1,17 +0,0 @@
|
||||
# shows tracks for the given artist
|
||||
|
||||
# usage: python tracks.py [artist name]
|
||||
|
||||
import sys
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
artist_name = ' '.join(sys.argv[1:])
|
||||
results = sp.search(q=artist_name, limit=20)
|
||||
for i, t in enumerate(results['tracks']['items']):
|
||||
print(' ', i, t['name'])
|
||||
@ -1,28 +0,0 @@
|
||||
# Shows all artists featured on an album
|
||||
|
||||
# usage: featured_artists.py spotify:album:[album urn]
|
||||
|
||||
import sys
|
||||
from pprint import pprint
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
urn = sys.argv[1]
|
||||
else:
|
||||
urn = 'spotify:album:5yTx83u3qerZF7GRJu7eFk'
|
||||
|
||||
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
|
||||
album = sp.album(urn)
|
||||
|
||||
featured_artists = set()
|
||||
|
||||
items = album['tracks']['items']
|
||||
|
||||
for item in items:
|
||||
for ele in item['artists']:
|
||||
if 'name' in ele:
|
||||
featured_artists.add(ele['name'])
|
||||
|
||||
pprint(featured_artists)
|
||||
@ -1,19 +0,0 @@
|
||||
# shows artist info for a URN or URL
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth())
|
||||
|
||||
response = sp.featured_playlists()
|
||||
print(response['message'])
|
||||
|
||||
while response:
|
||||
playlists = response['playlists']
|
||||
for i, item in enumerate(playlists['items']):
|
||||
print(playlists['offset'] + i, item['name'])
|
||||
|
||||
if playlists['next']:
|
||||
response = sp.next(playlists)
|
||||
else:
|
||||
response = None
|
||||
@ -1,22 +0,0 @@
|
||||
# Shows a user's saved tracks (need to be authenticated via oauth)
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'user-library-read'
|
||||
|
||||
|
||||
def show_tracks(results):
|
||||
for item in results['items']:
|
||||
track = item['track']
|
||||
print(f"{track['artists'][0]['name']:>32.32} {track['name']}")
|
||||
|
||||
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
|
||||
results = sp.current_user_saved_tracks()
|
||||
show_tracks(results)
|
||||
|
||||
while results['next']:
|
||||
results = sp.next(results)
|
||||
show_tracks(results)
|
||||
@ -1,18 +0,0 @@
|
||||
# shows artist info for a URN or URL
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth())
|
||||
|
||||
response = sp.new_releases()
|
||||
|
||||
while response:
|
||||
albums = response['albums']
|
||||
for i, item in enumerate(albums['items']):
|
||||
print(albums['offset'] + i, item['name'])
|
||||
|
||||
if albums['next']:
|
||||
response = sp.next(albums)
|
||||
else:
|
||||
response = None
|
||||
@ -1,25 +0,0 @@
|
||||
# shows related artists for the given seed artist
|
||||
|
||||
import sys
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
artist_name = sys.argv[1]
|
||||
else:
|
||||
artist_name = 'weezer'
|
||||
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
result = sp.search(q='artist:' + artist_name, type='artist')
|
||||
try:
|
||||
name = result['artists']['items'][0]['name']
|
||||
uri = result['artists']['items'][0]['uri']
|
||||
|
||||
related = sp.artist_related_artists(uri)
|
||||
print('Related artists for', name)
|
||||
for artist in related['artists']:
|
||||
print(' ', artist['name'])
|
||||
except BaseException:
|
||||
print("usage show_related.py [artist-name]")
|
||||
@ -1,17 +0,0 @@
|
||||
# shows track info for a URN or URL
|
||||
|
||||
import sys
|
||||
from pprint import pprint
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
urn = sys.argv[1]
|
||||
else:
|
||||
urn = 'spotify:track:0Svkvt5I79wficMFgaqEQJ'
|
||||
|
||||
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
|
||||
|
||||
track = sp.track(urn)
|
||||
pprint(track)
|
||||
@ -1,28 +0,0 @@
|
||||
'''
|
||||
usage: show_tracks.py path_of_ids
|
||||
|
||||
given a list of track IDs show the artist and track name
|
||||
'''
|
||||
import argparse
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Print artist and track name given a list of track IDs')
|
||||
parser.add_argument('-u', '--uris', nargs='+',
|
||||
required=True, help='Track ids')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth())
|
||||
track_list = sp.tracks(args.uris)
|
||||
for track in track_list['tracks']:
|
||||
print(track['name'] + ' - ' + track['artists'][0]['name'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,18 +0,0 @@
|
||||
# Shows artist info for a URN or URL
|
||||
|
||||
import pprint
|
||||
import sys
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
username = sys.argv[1]
|
||||
else:
|
||||
username = 'plamere'
|
||||
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
sp.trace = True
|
||||
user = sp.user(username)
|
||||
pprint.pprint(user)
|
||||
@ -1,16 +0,0 @@
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
birdy_uri = 'spotify:artist:2WX2uTcsvV5OnS0inACecP'
|
||||
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
|
||||
results = sp.artist_albums(birdy_uri, album_type='album')
|
||||
albums = results['items']
|
||||
while results['next']:
|
||||
results = sp.next(results)
|
||||
albums.extend(results['items'])
|
||||
|
||||
for album in albums:
|
||||
print(album['name'])
|
||||
@ -1,14 +0,0 @@
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
lz_uri = 'spotify:artist:36QJpDe2go2KgaRleHCDTp'
|
||||
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
|
||||
results = sp.artist_top_tracks(lz_uri)
|
||||
|
||||
for track in results['tracks'][:10]:
|
||||
print('track : ' + track['name'])
|
||||
print('audio : ' + track['preview_url'])
|
||||
print('cover art: ' + track['album']['images'][0]['url'])
|
||||
@ -1,13 +0,0 @@
|
||||
from pprint import pprint
|
||||
|
||||
import spotipy
|
||||
|
||||
|
||||
def main():
|
||||
spotify = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth())
|
||||
me = spotify.me()
|
||||
pprint(me)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1,9 +0,0 @@
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
|
||||
results = sp.search(q='weezer', limit=20)
|
||||
for i, t in enumerate(results['tracks']['items']):
|
||||
print(' ', i, t['name'])
|
||||
@ -1,18 +0,0 @@
|
||||
# Shows the name of the artist/band and their image by giving a link
|
||||
import sys
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
name = ' '.join(sys.argv[1:])
|
||||
else:
|
||||
name = 'Radiohead'
|
||||
|
||||
results = sp.search(q='artist:' + name, type='artist')
|
||||
items = results['artists']['items']
|
||||
if len(items) > 0:
|
||||
artist = items[0]
|
||||
print(artist['name'], artist['images'][0]['url'])
|
||||
@ -1,70 +0,0 @@
|
||||
import random
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
'''
|
||||
generates a list of songs where the first word in each subsequent song
|
||||
matches the last word of the previous song.
|
||||
|
||||
usage: python title_chain.py [song name]
|
||||
'''
|
||||
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
|
||||
|
||||
skiplist = {'dm', 'remix'}
|
||||
max_offset = 500
|
||||
seen = set()
|
||||
|
||||
|
||||
def find_songs_that_start_with_word(word):
|
||||
max_titles = 20
|
||||
max_offset = 200
|
||||
offset = 0
|
||||
|
||||
out = []
|
||||
while offset < max_offset and len(out) < max_titles:
|
||||
results = sp.search(q=word, type='track', limit=50, offset=offset)
|
||||
if len(results['tracks']['items']) == 0:
|
||||
break
|
||||
|
||||
for item in results['tracks']['items']:
|
||||
name = item['name'].lower()
|
||||
if name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
if '(' in name:
|
||||
continue
|
||||
if '-' in name:
|
||||
continue
|
||||
if '/' in name:
|
||||
continue
|
||||
words = name.split()
|
||||
if len(words) > 1 and words[0] == word \
|
||||
and words[-1] not in skiplist:
|
||||
# print " ", name, len(out)
|
||||
out.append(item)
|
||||
offset += 50
|
||||
# print "found", len(out), "matches"
|
||||
return out
|
||||
|
||||
|
||||
def make_chain(word):
|
||||
which = 1
|
||||
while True:
|
||||
songs = find_songs_that_start_with_word(word)
|
||||
if len(songs) > 0:
|
||||
song = random.choice(songs)
|
||||
print(which, song['name'] + " by " + song['artists'][0]['name'])
|
||||
which += 1
|
||||
word = song['name'].lower().split()[-1]
|
||||
else:
|
||||
break
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
title = ' '.join(sys.argv[1:])
|
||||
make_chain(sys.argv[1].lower())
|
||||
@ -1,43 +0,0 @@
|
||||
import random
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
# Set up Spotify credentials
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
|
||||
client_id="YOUR_APP_CLIENT_ID",
|
||||
client_secret="YOUR_APP_CLIENT_SECRET",
|
||||
redirect_uri="YOUR_APP_REDIRECT_URI",
|
||||
scope="user-top-read,user-library-read,user-read-recently-played"))
|
||||
|
||||
# Get the user's top tracks
|
||||
top_tracks = sp.current_user_top_tracks(limit=10, time_range='long_term')
|
||||
|
||||
# Get the user's liked tracks
|
||||
liked_tracks = sp.current_user_saved_tracks(limit=10)
|
||||
|
||||
# Get the user's listening history
|
||||
history = sp.current_user_recently_played(limit=10)
|
||||
|
||||
# Extract a list of the top track IDs
|
||||
top_track_ids = [track['id'] for track in top_tracks['items']]
|
||||
|
||||
# Extract a list of the liked track IDs
|
||||
liked_track_ids = [track['track']['id'] for track in liked_tracks['items']]
|
||||
|
||||
# Extract a list of the history track IDs
|
||||
history_track_ids = [track['track']['id'] for track in history['items']]
|
||||
|
||||
# Combine the three lists and shuffle them randomly
|
||||
seed_track_ids = top_track_ids + liked_track_ids + history_track_ids
|
||||
random.shuffle(seed_track_ids)
|
||||
|
||||
# Use the IDs to get some recommendations
|
||||
# Note: the seed_tracks parameter can accept up to 5 tracks
|
||||
recommendations = sp.recommendations(
|
||||
seed_tracks=seed_track_ids[0:5], limit=10, country='US')
|
||||
|
||||
# Display the recommendations
|
||||
for i, track in enumerate(recommendations['tracks']):
|
||||
print(f"{i+1}. {track['name']} by "
|
||||
f"{', '.join([artist['name'] for artist in track['artists']])}")
|
||||
@ -1,33 +0,0 @@
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'playlist-modify-public'
|
||||
|
||||
logger = logging.getLogger('examples.unfollow_playlist')
|
||||
logging.basicConfig(level='DEBUG')
|
||||
|
||||
'''
|
||||
Spotify doesn't have a dedicated endpoint for deleting a playlist. However,
|
||||
unfollowing a playlist has the effect of deleting it from the user's account.
|
||||
When a playlist is removed from the user's account, the system unfollows it,
|
||||
and then no longer shows it in playlist list.'''
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Unfollows a playlist')
|
||||
parser.add_argument('-p', '--playlist', required=True,
|
||||
help='Playlist id')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
sp.current_user_unfollow_playlist(args.playlist)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,20 +0,0 @@
|
||||
# Shows a user's playlists (need to be authenticated via oauth)
|
||||
|
||||
import sys
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
username = sys.argv[1]
|
||||
else:
|
||||
print("Whoops, need a username!")
|
||||
print("usage: python user_playlists.py [username]")
|
||||
sys.exit()
|
||||
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth())
|
||||
|
||||
playlists = sp.user_playlists(username)
|
||||
|
||||
for playlist in playlists['items']:
|
||||
print(playlist['name'])
|
||||
@ -1,31 +0,0 @@
|
||||
# Shows a user's playlists (need to be authenticated via oauth)
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
|
||||
def show_tracks(results):
|
||||
for i, item in enumerate(results['items']):
|
||||
track = item['track']
|
||||
print(f" {i} {track['artists'][0]['name']:>32.32} {track['name']}")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
scope = 'playlist-read-private'
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
|
||||
playlists = sp.current_user_playlists()
|
||||
user_id = sp.me()['id']
|
||||
|
||||
for playlist in playlists['items']:
|
||||
if playlist['owner']['id'] == user_id:
|
||||
print()
|
||||
print(playlist['name'])
|
||||
print(' total tracks', playlist['tracks']['total'])
|
||||
|
||||
tracks = sp.playlist_items(playlist['id'], fields="items,next", additional_types=('tracks', ))
|
||||
show_tracks(tracks)
|
||||
|
||||
while tracks['next']:
|
||||
tracks = sp.next(tracks)
|
||||
show_tracks(tracks)
|
||||
@ -1,26 +0,0 @@
|
||||
# Gets all the public playlists for the given
|
||||
# user. Uses Client Credentials flow
|
||||
#
|
||||
|
||||
import sys
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
|
||||
user = 'spotify'
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
user = sys.argv[1]
|
||||
|
||||
playlists = sp.user_playlists(user)
|
||||
|
||||
while playlists:
|
||||
for i, playlist in enumerate(playlists['items']):
|
||||
print(f"{i + 1 + playlists['offset']:4d} {playlist['uri']} {playlist['name']}")
|
||||
if playlists['next']:
|
||||
playlists = sp.next(playlists)
|
||||
else:
|
||||
playlists = None
|
||||
@ -1,12 +0,0 @@
|
||||
# Deletes user saved album
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'user-library-modify'
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
|
||||
uris = input("input a list of album URIs, URLs or IDs: ")
|
||||
uris = list(map(str, uris.split()))
|
||||
deleted = sp.current_user_saved_albums_delete(uris)
|
||||
print("Deletion successful.")
|
||||
@ -1,30 +0,0 @@
|
||||
"""
|
||||
List current user's saved episodes
|
||||
Usage: user_saved_episodes -l <num> -o <num>
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'user-library-read'
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Show user\'s saved episodes')
|
||||
parser.add_argument('-l', '--limit', default=20, help='Num of episodes to return')
|
||||
parser.add_argument('-o', '--offset', default=0, help='Index of first show to return')
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
results = sp.current_user_saved_episodes(limit=args.limit, offset=args.offset)
|
||||
# Print episode names
|
||||
for item in results['items']:
|
||||
print(item['episode']['name'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,30 +0,0 @@
|
||||
"""
|
||||
List current user's saved shows
|
||||
Usage: user_saved_shows -l <num> -o <num>
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
scope = 'user-library-read'
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Show user\'s saved shows')
|
||||
parser.add_argument('-l', '--limit', default=20, help='Num of shows to return')
|
||||
parser.add_argument('-o', '--offset', default=0, help='Index of first show to return')
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
results = sp.current_user_saved_shows(limit=args.limit, offset=args.offset)
|
||||
# Print episode names
|
||||
for item in results['items']:
|
||||
print(item['show']['name'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Loading…
Reference in New Issue
Block a user