Apple Scriptだけでtwitterに今聴いてる曲をポストする
以前書いたスクリプトはシェルからcurl呼んでたから、今度はApple Scriptだけでtwitterに今聴いてる曲をポストする様にしてみた。
あんまりきれいじゃないけど、Apple Scriptって情報が少ないから、iTunesからの情報取得、URL Access Scripting、常駐的な処理、のサンプルになれば良いな。
あと、テンポラリファイルの取得とかも、あんまり情報がなかった。。
ちなみに、POSTする先のURLを変えればnowaのナニシテルにも投稿できた。けど、日本語が化ける。URL Encodeすれば解消する、かな?
POSTするだけして、結果を気にしなくていいなら割と簡単だけど、結果を見る必要がある場合は、テンポラリファイルに一旦保存して、読込む、様な処理が必要そう。
文字列のパースとかライブラリがあれば楽だけど、無さそうだから、めんどくさそうだけどね。。。
set conf_delay to 30 set conf_msg to "now playing: " set conf_user to "USERNAME" set conf_pass to "PASSWORD" -- set prev_track to "" on get_itunes_currenttrack() -- check if iTunes is active and playing tell application "System Events" if (application process "iTunes" exists) then set is_iTunes to true tell application "iTunes" -- check if iTunes is playing or not if player state is playing then set currenttrack to current track set track_info to (name of currenttrack & " / " & artist of currenttrack) if (rating of currenttrack > 0) then set track_info to track_info & " (" repeat (rating of currenttrack) / 20 times set track_info to track_info & "*" end repeat set track_info to track_info & ")" end if else set track_info to false end if end tell else set track_info to false end if end tell return track_info end get_itunes_currenttrack on update_status(_message) global conf_user global conf_pass set tmpfile to (((path to temporary items from user domain as text) & "iTunes2twitter.log") as Unicode text) try with timeout of 20 seconds tell application "URL Access Scripting" activate set twitter_URL to "http://" & conf_user & ":" & conf_pass & "@twitter.com/statuses/update.json" download twitter_URL to tmpfile replacing yes form data "status=" & _ end tell end timeout on error log "error: url access fail" end try log _message end update_status on timer_handle(__delay, _prev_track) global conf_msg set current_track to get_itunes_currenttrack() if current_track = _prev_track then log "identical" else if current_track is not false then log "track changed!" set twitter_msg to conf_msg & current_track update_status(twitter_msg) end if end if return current_track end timer_handle on timer_loop(_delay) set prev_track to "" repeat set prev_track to timer_handle(_delay, prev_track) delay _delay end repeat end timer_loop log "here we go" timer_loop(conf_delay)