Skip to content

Instantly share code, notes, and snippets.

@PMaynard
Created April 21, 2016 13:27
Show Gist options
  • Save PMaynard/d945bf7dac85b1b6a67271b378c76e1a to your computer and use it in GitHub Desktop.
Save PMaynard/d945bf7dac85b1b6a67271b378c76e1a to your computer and use it in GitHub Desktop.
Last.fm youtube downloader
#!/usr/bin/python
# pip install --upgrade google-api-python-client
import urllib2
import json
import time
import subprocess
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
YOUTUBE_DEVELOPER_KEY = "__"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
LAST_FM_API_KEY = "___"
LAST_FM_TIME = time.time()-4000 # about an hour
USERS = ["intel17"]
def youtube_search(track, max_results):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=YOUTUBE_DEVELOPER_KEY)
search_response = youtube.search().list(
q=track,
part="id,snippet",
maxResults=max_results
).execute()
videos = []
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
return("%s" % (search_result["id"]["videoId"]))
# Return the first found video id.
def lastfm_search(username):
# todo array of users
res = urllib2.urlopen("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user="+username+"&from="+str(LAST_FM_TIME)+"&api_key="+LAST_FM_API_KEY+"&format=json").read()
# todo: error check
recent_played = json.loads(res)
tracks = recent_played['recenttracks']['track']
rtn = []
for t in tracks:
rtn.append(t['name'] + " by " + t['artist']['#text'])
print "Tracks:\n", "\n".join(rtn), "\n"
return rtn
def download_track_id(id):
subprocess.call(["/usr/bin/youtube-dl", "--id", id, "--write-info-json", "--add-metadata", "-x", "--audio-format", "mp3"])
# TODO - Don't bother doing anything if we've already got it.
tracks = lastfm_search(USERS[0])
for t in tracks:
download_track_id(youtube_search(t, "1"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment