Last active
February 4, 2021 01:55
-
-
Save tclancy/f3f66a4a85c751d1210c897a7f86a271 to your computer and use it in GitHub Desktop.
Sends the items in The New Yorker's Night Life Listings to a Spotify Playlist
This file contains 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
#!/usr/bin/env python3 | |
import logging | |
from bs4 import BeautifulSoup | |
import requests | |
import spotipy | |
from spotipy.oauth2 import SpotifyOAuth | |
logger = logging.getLogger(__name__) | |
handler = logging.StreamHandler() | |
handler.setLevel(logging.DEBUG) | |
handler.setFormatter(logging.Formatter("%(asctime)s - %(message)s - [%(levelname)s]")) | |
logger.addHandler(handler) | |
logger.setLevel(logging.INFO) | |
NEW_YAWKA_PLAYLIST_ID = "3GBNA2bP7HiRHMpvka9JeR" | |
if __name__ == "__main__": | |
response = requests.get( | |
"https://www.newyorker.com/goings-on-about-town/night-life" | |
) | |
if response.status_code != 200: | |
raise SystemExit(f"Got status {response.status_code} from request") | |
bs = BeautifulSoup(response.content, features="html.parser") | |
lookups = [] | |
for item in bs.find_all("div", class_="grid-item"): | |
# let's not even bother being regex cool | |
lookups.append(item.h3.a.text.replace(":", "").replace('"', "")) | |
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope="playlist-modify-private")) | |
existing_items = [item["track"]["id"] for item in sp.playlist_items(NEW_YAWKA_PLAYLIST_ID)["items"]] | |
track_ids = [] | |
for term in lookups: | |
result = sp.search(q=term, limit=1) | |
if not result or not result.get("tracks", None): | |
continue | |
try: | |
track_id = result["tracks"]["items"][0]["id"] | |
if track_id in existing_items: | |
logger.info("Skipping %s as we already have it", term) | |
continue | |
track_ids.append(track_id) | |
except IndexError: | |
logger.warning("No luck for %s", term) | |
continue | |
logger.info("Adding %s to playlist", term) | |
if track_ids: | |
sp.playlist_add_items(NEW_YAWKA_PLAYLIST_ID, track_ids) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment