Created
January 30, 2015 22:37
-
-
Save vim13/b1978d5d586bbcb02853 to your computer and use it in GitHub Desktop.
last.fmでloveしたものをYouTube urlつきでtweet
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/local/bin/python | |
#vim:fileencoding=utf-8 | |
import re | |
import codecs | |
import time | |
import urllib2 | |
from pit import Pit | |
import tweepy | |
import BeautifulSoup | |
def parseHtml(uri): | |
my_uri = uri | |
html = urllib2.urlopen(my_uri).read() | |
soup = BeautifulSoup.BeautifulSoup(html) | |
return soup | |
def getId(soup): | |
article = soup.findAll('title') | |
ids = [opt.string for opt in article] | |
ids.pop(0) | |
return ids | |
def readFile(path): | |
opened_file = codecs.open(path, 'r', 'utf-8') | |
logs = [] | |
for line in opened_file: | |
logs.append(line[:-1]) | |
opened_file.close() | |
return logs | |
def writeFile(path, ids): | |
opend_file = open(path, 'w') | |
for x in ids: | |
opend_file.write(str(x)+'\n') | |
opend_file.close() | |
def checkId(ids, logs): | |
new = [] | |
for x in ids: | |
if x not in logs: | |
new.append(x) | |
return new | |
def postTweet(title, api): | |
for x in title: | |
api.update_status('I Loved "'+ x['title'].encode('utf-8') + '" via last.fm https://www.youtube.com/watch?v=' + x['src'].encode('utf-8')) | |
time.sleep(10) | |
def youtube(new, uri2): | |
videos = [] | |
for x in new: | |
url = uri2 + str(x) | |
url = url.replace('–', '') | |
url = url.replace(' ', '%20') | |
soup = parseHtml(url) | |
select = soup.find('div',{'class':'yt-thumb video-thumb'}) | |
if select: | |
src = re.search('vi\/(.*?)\/mqdef', str(select)).group(1)[:94] | |
dic = {'src':src, 'title':x} | |
videos.append(dic) | |
return videos | |
if __name__ == '__main__': | |
key = Pit.get('twitter.com') | |
consumer_key = key['consumer_key'] | |
consumer_secret = key['consumer_secret'] | |
access_token = key['access_token'] | |
access_token_secret = key['access_token_secret'] | |
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) | |
auth.set_access_token(access_token, access_token_secret) | |
api = tweepy.API(auth) | |
uri = 'http://ws.audioscrobbler.com/2.0/user/vim13/lovedtracks.rss' | |
uri2 = 'http://www.youtube.com/results?search_query=' | |
soup = parseHtml(uri) | |
ids = getId(soup) | |
path = 'favs.txt' | |
logs = readFile(path) | |
new = checkId(ids, logs) | |
writeFile(path, ids) | |
if new: | |
videos = youtube(new, uri2) | |
postTweet(videos, api) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment