slack hubotを使ってみる
slack hubotを使って遅延情報を取得する
の続々編。
今回は、openweathermapAPIを使って天気予報を取得してみたいと思います。
ほんと色々参考になるサイトがあって楽勝にできました(ほんとありがたい!)。
今回参考にしたのは以下のサイト。
【Hubot】天気を教えてくれるBot
#API Keyを取得
openweathermap
に登録して、↓からAPI Keyを取得しましょう。
都市一覧はここから取れるみたいです。
http://openweathermap.org/help/city_list.txt
#コードを書く
scripts/ にコードを書きます。
apikeyには取得したAPIkeyを入れるだけ。
↓な感じ。横浜と東京の天気を毎朝8時にお知らせしてくれます。また、「weather Yokohama」と尋ねるといつでも教えてくれる感じなってます。
cronJob = require('cron').CronJob
module.exports = (robot) ->
robot.respond /weather (.+)/i, (msg) ->
target = msg.match[1]
apikey = ""
params = "q=#{target},jp&appid=#{apikey}&units=metric"
searchWeather(params, target, msg)
searchWeather = (url, place, msg) ->
request = robot.http("http://api.openweathermap.org/data/2.5/weather?#{url}").get()
stMessage = request (err, res, body) ->
json = JSON.parse body
if json['cod'] != 200
#APIerror
msg.send ":warning:" + json['message']
return
weatherName = json['weather'][0]['main']
icon = json['weather'][0]['icon']
temp = json['main']['temp']
temp_max = json['main']['temp_max']
temp_min = json['main']['temp_min']
msg.send "今日の#{place}の天気は「" + weatherName + "」です。\n気温:"+ temp + "℃ 最高気温:" + temp_max+ "℃ 最低気温:" + temp_min + "℃\nhttp://openweathermap.org/img/w/" + icon + ".png"
new cronJob('0 0 8 * * *', () ->
apikey = ""
#東京
tokyo = "q=Tokyo,jp&appid=#{apikey}&units=metric"
#横浜
yokohama = "q=Yokohama,jp&appid=#{apikey}&units=metric"
searchWeatherCron(yokohama, "横浜")
searchWeatherCron(tokyo, "東京")
).start()
searchWeatherCron = (url, place) ->
request = robot.http("http://api.openweathermap.org/data/2.5/weather?#{url}").get()
stMessage = request (err, res, body) ->
json = JSON.parse body
weatherName = json['weather'][0]['main']
icon = json['weather'][0]['icon']
temp = json['main']['temp']
temp_max = json['main']['temp_max']
temp_min = json['main']['temp_min']
sendMessage = "今日の#{place}の天気は「" + weatherName + "」です。\n気温:"+ temp + "℃ 最高気温:" + temp_max+ "℃ 最低気温:" + temp_min + "℃\nhttp://openweathermap.org/img/w/" + icon + ".png"
robot.send {room: "#weather_info"}, sendMessage
#実行
実行するのみ〜
$ HUBOT_SLACK_TOKEN=<HUBOT_SLACK_TOKEN>./bin/hubot --adapter slack
きました〜今回は以上です。