Last active
March 7, 2016 18:57
-
-
Save jefftriplett/69c4f0358e0779bf2942 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Formatting based on: | |
https://en.wikipedia.org/wiki/Wikipedia:WikiProject_Albums/Album_article_style_guide | |
Method inspired from: | |
- https://github.com/plamere/spotipy/blob/master/examples/user_playlists_contents.py | |
- https://github.com/jacobian/rdio-takeout-importer/blob/master/r2s.py#L68 | |
Getting started: | |
$ pip install click spotipy | |
""" | |
import click | |
import os | |
import spotipy | |
import spotipy.util | |
USERNAME = os.environ.get('SPOTIFY_USERNAME') | |
CLIENT_ID = os.environ.get('SPOTIFY_CLIENT_ID') | |
CLIENT_SECRET = os.environ.get('SPOTIFY_CLIENT_SECRET') | |
REDIRECT_URI = os.environ.get('SPOTIFY_REDIRECT_URI', '') | |
TOKEN = os.environ.get('SPOTIFY_TOKEN', '') | |
def connect_to_spotify(): | |
if len(TOKEN): | |
return spotipy.Spotify(auth=TOKEN) | |
else: | |
token = spotipy.util.prompt_for_user_token( | |
USERNAME, | |
scope='playlist-read-private playlist-read-collaborative', | |
client_id=CLIENT_ID, | |
client_secret=CLIENT_SECRET, | |
redirect_uri=REDIRECT_URI) | |
return spotipy.Spotify(auth=token) | |
def show_tracks(results): | |
tracks = results['items'] | |
for result in tracks: | |
track = result['track'] | |
click.echo('- ["{name}"]({href}) ({artist})'.format( | |
artist=track['artists'][0]['name'], | |
name=track['name'], | |
href=track['external_urls']['spotify'] if 'spotify' in track['external_urls'] else '', | |
)) | |
@click.command() | |
@click.argument('username') | |
@click.option('--playlist', default='') | |
def main(username, playlist): | |
if len(playlist): | |
playlist_names = playlist.split(',') | |
else: | |
playlist_names = [] | |
spotify = connect_to_spotify() | |
playlists = spotify.user_playlists(username) | |
for playlist in playlists['items']: | |
if len(playlist_names) and playlist['name'] not in playlist_names: | |
click.echo('skipping: {0}'.format(playlist['name'])) | |
continue | |
click.echo("## {0}".format(playlist['name'])) | |
click.echo() | |
owner = playlist['owner']['id'] | |
results = spotify.user_playlist(owner, playlist['id'], fields='tracks,next') | |
tracks = results['tracks'] | |
show_tracks(tracks) | |
while tracks['next']: | |
tracks = spotify.next(tracks) | |
show_tracks(tracks) | |
click.echo() | |
click.echo('---') | |
click.echo() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment