2016-05-09

LINE BOT APIを利用して雨が降りそうな時は通知するようにしてみる

このエントリーをブックマークに追加 このエントリーを含むはてなブックマーク
※サンプルをLINE BOT APIからLINE Messaging APIに書き換えたものを以下で公開しました。
https://kingyo-bachi.blogspot.jp/2017/04/line-bot-apiline-messaging-api.html

LINEで電車遅延情報を送ってみる

LINEでGoogle Calendarの情報を送ってみる
に続きLINEで雨が降りそうな時に通知してみることにしてみます。

天気に関する情報を取得する手段はいろいろあるのですが、降水確率を取得する手段はあまりなく、以下ぐらいしか見つけられませんでした。
http://www.drk7.jp/weather/
こちらを活用させていただきます。

家を出る直前ぐらいにLINEで通知する感じにして祝日は通知しないようにしたいと思います。

以下のような感じになります。

# coding: utf-8
require 'rest-client'
require 'json'
require 'date'
require 'holiday_jp'
require 'gmail'
require 'rexml/document'
class MyMail
#GMail関連の設定
ID = "GMail address"
PW = "GMail password"
TO = "mail send to address"
def self.send(sbj,msg)
gmail = Gmail.new(ID, PW)
message =
gmail.generate_message do
to TO
subject sbj
body msg
end
gmail.deliver(message)
gmail.logout
end
end
class LineBot
#LINE関連の設定
ID = "Channel ID"
SECRET = "Channel Secret"
MID = "MID"
TO = "送信先のID"
def self.send(msg)
headers = {
"Content-Type" => "application/json; charser=UTF-8",
"X-Line-ChannelID" => ID,
"X-Line-ChannelSecret" => SECRET,
"X-Line-Trusted-User-With-ACL" => MID
}
params = {
to: [TO],
toChannel: "1383378250",
eventType: "138311608800106203",
content: {
contentType: 1,
toType: 1,
text: msg,
}
}
RestClient.post "https://trialbot-api.line.me/v1/events", params.to_json, headers
end
end
class RainChk
#降水確率を取得したい地域情報
#以下を確認して設定する
#http://www.drk7.jp/weather/
#以下は東京の例
PREF = "http://www.drk7.jp/weather/xml/13.xml"
AREA = "東京地方"
def self.get_info(day,limit)
begin
response = RestClient.get PREF
rescue => e
p e.response
end
doc = REXML::Document.new response.to_str
day = day.strftime("%Y/%m/%d")
ret = {}
ret[:rain] = false
ret[:info] = []
doc.elements.each("weatherforecast/pref/area[@id='#{AREA}']/info[@date='#{day}']/rainfallchance/period") do |element|
next if element.attributes["hour"] == "00-06"
ret[:info].push [element.attributes["hour"],element.text + "%"]
ret[:rain] = true if element.text.to_i >= limit
end
ret
end
end
if HolidayJp.holiday?(Date.today)
print "#{Time.now.to_s} holiday!\n"
exit
end
#確認したい日付と降水確率が何%以上で雨を降るとみなすかの閾値を渡す
ret = RainChk.get_info Date.today,50
if ret[:rain]
msg = "雨が降るかもしれません。"
ret[:info].each do |a|
msg = msg + "\n #{a[0]} #{a[1]}"
end
begin
LineBot.send(msg)
rescue => e
print "#{Time.now.to_s} line bot error raise!\n"
MyMail.send "line bot error raise",e.response
exit
end
print "#{Time.now.to_s} rainy day!\n"
else
print "#{Time.now.to_s} sunny day.\n"
end
view raw rain_chk.rb hosted with ❤ by GitHub


これを以下のような感じでcron設定して月曜から金曜までの出勤前の6:50に動作するようにしました。
50 6 * * 1,2,3,4,5 /usr/bin/ruby /home/hogehoge/ruby/line_bot/rain_chk.rb >> /home/hogehoge/ruby/line_bot/rain_chk.log

毎日、朝お天気アプリを見て天気を見ているのに、出る直前には傘を持つことを忘れてしまうので何かの形でわかるようにしたいと思ったわけです。

一番よいのは傘が置いてあるところでわかりやすく気付ける形になれればよいのですけどね。


0 件のコメント: