Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Examples directory updates #1055

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added integration tests for audiobook endpoints.
- Removed `python 2.7` from GitHub Actions CI workflow. Python v2.7 reached end of life support and is no longer supported by Ubuntu 20.04.
- Removed `python 3.6` from GitHub Actions CI workflow. Ubuntu 20.04 is not available in GitHub Actions for `python 3.6`.
- Added examples for audiobooks, shows and episodes methods to examples directory

### Changed
- Changes the YouTube video link for authentication tutorial (the old video was in low definition, the new one is in high definition)
- Updated links to Spotify in documentation

### Fixed
- Fixed scripts in examples directory that didn't run correctly

## [2.23.0] - 2023-04-07

### Added
Expand Down
28 changes: 28 additions & 0 deletions examples/add_saved_episodes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""
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()
28 changes: 28 additions & 0 deletions examples/add_saved_shows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""
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()
31 changes: 31 additions & 0 deletions examples/check_show_is_saved.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""
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()
28 changes: 28 additions & 0 deletions examples/delete_saved_episodes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""
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()
21 changes: 8 additions & 13 deletions examples/follow_playlist.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@
import argparse
# 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')
parser.add_argument('-p', '--playlist', required=True, help='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()

if args.playlist is None:
# Uses the Spotify Global Top 50 playlist
spotipy.Spotify(auth_manager=SpotifyOAuth()).current_user_follow_playlist(
'37i9dQZEVXbMDoHDwVN2tF')

else:
spotipy.Spotify(auth_manager=SpotifyOAuth()).current_user_follow_playlist(args.playlist)

sp.current_user_follow_playlist(args.playlist)

if __name__ == '__main__':
main()
main()
29 changes: 29 additions & 0 deletions examples/get_audiobook_chapters_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
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()
29 changes: 29 additions & 0 deletions examples/get_audiobooks_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
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()
12 changes: 0 additions & 12 deletions examples/playlist_add_items.py

This file was deleted.

2 changes: 1 addition & 1 deletion examples/read_a_playlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

playlist_id = 'spotify:user:spotifycharts:playlist:37i9dQZEVXbJiZcmkrIHGU'
playlist_id = '37i9dQZEVXbJiZcmkrIHGU'
results = sp.playlist(playlist_id)
print(json.dumps(results, indent=4))
4 changes: 2 additions & 2 deletions examples/remove_tracks_from_playlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@


if len(sys.argv) > 2:
playlist_id = sys.argv[2]
track_ids = sys.argv[3:]
playlist_id = sys.argv[1]
track_ids = sys.argv[2:]
else:
print("Usage: %s playlist_id track_id ..." % (sys.argv[0]))
sys.exit()
Expand Down
2 changes: 1 addition & 1 deletion examples/replace_tracks_in_playlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import spotipy
from spotipy.oauth2 import SpotifyOAuth

if len(sys.argv) > 3:
if len(sys.argv) > 2:
playlist_id = sys.argv[1]
track_ids = sys.argv[2:]
else:
Expand Down
File renamed without changes.
34 changes: 19 additions & 15 deletions examples/show_tracks.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,25 @@

given a list of track IDs show the artist and track name
'''
from spotipy.oauth2 import SpotifyClientCredentials
import sys
from spotipy.oauth2 import SpotifyOAuth
import spotipy
import argparse


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()

if __name__ == '__main__':
max_tracks_per_call = 50
if len(sys.argv) > 1:
file = open(sys.argv[1])
else:
file = sys.stdin
tids = file.read().split()

client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
for start in range(0, len(tids), max_tracks_per_call):
results = sp.tracks(tids[start: start + max_tracks_per_call])
for track in results['tracks']:
print(track['name'] + ' - ' + track['artists'][0]['name'])
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()
11 changes: 0 additions & 11 deletions examples/test.py

This file was deleted.

6 changes: 4 additions & 2 deletions examples/unfollow_playlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import spotipy
from spotipy.oauth2 import SpotifyOAuth

scope = 'playlist-modify-public'

logger = logging.getLogger('examples.unfollow_playlist')
logging.basicConfig(level='DEBUG')

Expand All @@ -23,9 +25,9 @@ def get_args():

def main():
args = get_args()
sp = spotipy.Spotify(auth_manager=SpotifyOAuth())
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
sp.current_user_unfollow_playlist(args.playlist)


if __name__ == '__main__':
main()
main()
29 changes: 29 additions & 0 deletions examples/user_saved_episodes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
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()
Loading
Loading