The jonki

呼ばれて飛び出てじょじょじょじょーんき

【Mac】MacでiTunesで再生中の曲をYoutubeのリンクと共にツイートする

これの続き。今までJavaでやってたことPythonMacでもようやくできるようになった。
【Mac】MacでiTunesで再生中の曲をツイートする。

まずは結果から

$ python tweetSong.py 
キスをしようよ YUKI http://goo.gl/BafaS #nowplaying

ソース

tweet.scpt iTunes情報取得
tell application "iTunes"
        set m_artist to artist of current track
        set m_song to name of current track
        set m_info to m_song & " " & m_artist
end tell


で、こっちがツイートするPythonのプログラム。例外処理はまったくやってないです。

tweetSong.py
# /usr/bin/python
# -*- coding: utf-8 -*-

import tweepy
import os
import subprocess

import simplejson
import urllib, urllib2

consumer_key = 'xxx'
consumer_secret = 'xxx'

access_key = 'xxx'
access_secret = 'xxx'

ytube_base = 'http://www.youtube.com/results?search_category=10&search_type=videos&suggested_categories=10&uni=3&search_query='

def post(message):
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_key, access_secret)
        api = tweepy.API(auth_handler=auth)
        api.update_status(message)

def getCurrentSong():
        info = subprocess.check_output(['osascript ' + os.getcwd()+'/tweet.scpt'], shell=True)
        return info

def getShortUrl(_longUrl):
        req = urllib2.Request('https://www.googleapis.com/urlshortener/v1/url')
        data = "{'longUrl' : '%s'}" % _longUrl
        req.add_data(data)
        req.add_header('Content-Type', 'application/json')
        r = urllib2.urlopen(req)
        res = simplejson.loads(r.read())
        r.close()
        return res['id']

def getYoutubeUrl(info):
        ytube_url = ytube_base + urllib.quote(info.encode('utf-8'))
        ytube_url = getShortUrl(ytube_url)
        return ytube_url

def main():
        info = getCurrentSong().rstrip()
        ytube_url = getYoutubeUrl(info)
        tweet = info + ' ' + ytube_url + ' #nowplaying'
        print tweet
        post(tweet)

main()