2008年2月12日火曜日

weather hack

天気予報で降水確率が40%以上だったら、傘忘れないでね〜メールを
携帯に送るスクリプトを作りました。

天気予報データからXMLでデータを取得する。
自分の住まいのエリアの1日分の降水確率で40%以上があれば
予報データを組み立て携帯へ送信する。

携帯へはgmailを利用。gmailerというrubyのライブラリが必要です。

後は、crontab or タスクリストへ朝自動で起動する用にしておくだけです。
rubyなのでサクッとできました。

require 'net/http'
require 'gmailer'
require 'rexml/document'

host="www.drk7.jp"
path="/weather/xml/14.xml"

user="gmailのID"
pass="gmailのパスワード"
cellphone="携帯のアドレス"

#降水確率の基準値 メール送るか送らないか
RAINFALL_RATE=40

resp = ""
Net::HTTP.version_1_2

Net::HTTP.start(host, 80) {|http|
response = http.get(path)
if response.code != "200"
raise HttpError, "Http Conection Error."
end
resp = response.body
}

send_flag=false

body = "傘!!\n"
body << "神奈川県東部\n"
doc = REXML::Document.new(resp)
doc.elements.each("./weatherforecast/pref/area/info") do |item|
if item.attributes["date"] == Time.now.strftime("%Y/%m/%d")
#and doc.elements.each("./weatherforecast/pref/area").attributes["id"] == "東部"
body << item.text("weather") + "\n"
body << "降水確率\n"
4.times do |i|
period = item.get_elements("./rainfallchance/period")[i].text
hour = item.get_elements("./rainfallchance/period")[i].attributes["hour"]
body << "#{hour} #{period}\n"
begin
send_flag = true if period.to_i >= RAINFALL_RATE
rescue
end
end
body << item.text("weather_detail") + "\n"
# 西部をスキップする
break
end
end

puts body

if send_flag
GMailer.connect(user, pass) do |g|
g.send(
:to => cellphone,
:subject => "weather hack",
:body => body)
end
end


メールのイメージ
傘!!
神奈川県東部
くもり時々雨
降水確率
00-06 --
06-12 60
12-18 50
18-24 30
北の風のちやや強く海上では後北の風強くくもり朝から昼過ぎ雨

0 件のコメント:

干し芋のリスト