import json import datetime as dt import sys import numpy import time from ytmusicapi import YTMusic ytmusic = YTMusic("config.json") # created a config file following the docs here: https://ytmusicapi.readthedocs.io/en/latest/setup.html # I tried the "interactive" authentication but wasn't having luck with it def get_playlistID(name): playlistID = ytmusic.get_library_playlists(limit=100) for i in playlistID: if i['title'] == name: return i['playlistId'] if sys.argv[1]: to_shuffle = str(sys.argv[1]) to_shuffleID = get_playlistID(to_shuffle) else: print("Usage: shuffler.py playlistname") sys.exit() try: backup = sys.argv[2] # back up the playlist if requested bkup_title = to_shuffle + ' autobackup' if get_playlistID(bkup_title): ytmusic.delete_playlist(get_playlistID(bkup_title)) backup = {} backup['source_playlist'] = to_shuffleID backup['title'] = bkup_title now = dt.datetime.now() now = now.strftime("%Y-%m-%d %H:%M") backup['description'] = 'Created ' + now ytmusic.create_playlist(**backup) print(f'{bkup_title} created') except: track_ids = [] # Python needs SOMETHING here, whatever. playlist = ytmusic.get_playlist(to_shuffleID) #get the songs in the playlist track_ids = [] for i in playlist['tracks']: track_ids.append(i['videoId']) numpy.random.shuffle(track_ids) ytmusic.remove_playlist_items(to_shuffleID, playlist['tracks']) time.sleep(5) # having the requests too close together was causing errors ytmusic.add_playlist_items(to_shuffleID, track_ids) now = dt.datetime.now() now = now.strftime("%Y-%m-%d %H:%M") shuffled = {} shuffled['playlistId'] = to_shuffleID shuffled['description'] = 'Shuffled ' + now ytmusic.edit_playlist(**shuffled) print(f'The playlist called \"{to_shuffle}\" has been shuffled!')