YTM-Shuffler/shuffler.py

60 lines
1.8 KiB
Python
Raw Permalink Normal View History

2022-05-20 14:38:39 -05:00
import json
import datetime as dt
2022-05-20 15:25:56 -05:00
import sys
2023-04-06 10:06:24 -05:00
import numpy
import time
2022-05-20 14:38:39 -05:00
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']
2022-05-23 15:21:20 -05:00
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))
2023-04-06 10:06:24 -05:00
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')
2022-05-23 15:21:20 -05:00
except:
track_ids = [] # Python needs SOMETHING here, whatever.
2023-04-06 10:06:24 -05:00
playlist = ytmusic.get_playlist(to_shuffleID) #get the songs in the playlist
2022-05-20 14:38:39 -05:00
track_ids = []
for i in playlist['tracks']:
track_ids.append(i['videoId'])
2022-05-23 15:21:20 -05:00
2023-04-06 10:06:24 -05:00
numpy.random.shuffle(track_ids)
2022-05-20 14:38:39 -05:00
2022-05-23 15:21:20 -05:00
ytmusic.remove_playlist_items(to_shuffleID, playlist['tracks'])
2023-04-06 10:06:24 -05:00
time.sleep(5) # having the requests too close together was causing errors
2022-05-23 15:21:20 -05:00
ytmusic.add_playlist_items(to_shuffleID, track_ids)
2022-05-20 14:38:39 -05:00
2023-04-06 10:06:24 -05:00
2022-05-20 14:38:39 -05:00
now = dt.datetime.now()
now = now.strftime("%Y-%m-%d %H:%M")
2022-05-23 15:21:20 -05:00
shuffled = {}
shuffled['playlistId'] = to_shuffleID
2022-05-20 14:38:39 -05:00
shuffled['description'] = 'Shuffled ' + now
2022-05-23 15:21:20 -05:00
ytmusic.edit_playlist(**shuffled)
2022-05-20 15:25:56 -05:00
print(f'The playlist called \"{to_shuffle}\" has been shuffled!')