Hubotを利用してSlackで天気を定期的に教えてくれる。
またはBotに聞いたら教えてくれるスクリプトを書いてみました。
使用するAPIは「OenWeatherMap」です。
無料である程度使えますが、更新間隔が1〜2時間ごとらしいので、
急な天候の変化については弱いかもです(:3_ヽ)_
APIのパラメーターは下記のとおりです。
【パラメータ(一部)】
| パラメータ | 説明 | 値 | 備考 | 
|---|---|---|---|
| q | 温度の単位を指定する | ({都市名},{国コード(ISO3166)} | q=Tokyo,jp 東京の天気  | 
| mode | 取得形式を指定する | (省略時) | JSON形式 | 
| xml | XML形式 | ||
| html | HTML形式 | ||
| units | 温度の単位を指定する | (省略時) | ケルビン | 
| metric | 摂氏(°C) | ||
| imperial | 華氏(°F) | 
下のコードはSlack上で「今日の天気」と書き込んだ時に天気を教えてくれるコードです。
# Description:
#   今日の天気を教えてくれます。
#
# Commands:
#   今日の天気
#
module.exports = (robot) ->
	send = (msg) -> 
		request = robot.http("http://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp&appid=APIKEY&units=metric").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']
			msg.send "今日の東京の天気は「" + weatherName + "」です。\n気温:"+ temp + "℃ 最高気温:"  + temp_max+ "℃ 最低気温:" + temp_min + "℃\nhttp://openweathermap.org/img/w/" + icon + ".png"
	robot.hear /今日の天気/, (msg) ->
		send(msg)
Slack上での実行結果です。
天気を聞いた時
下はCronJobを利用した定時実行版です。
cron = require('cron').CronJob
module.exports = (robot) ->
  sendWeather = (channel) -> 
    request = robot.http("http://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp&appid=[APIKEY]&units=metric").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 = "今日の東京の天気は「" + weatherName + "」です。\n気温:"+ temp + "℃ 最高気温:"  + temp_max+ "℃ 最低気温:" + temp_min + "℃\nhttp://openweathermap.org/img/w/" + icon + ".png"
      robot.send {room: channel}, sendMessage
   new cron('0 0 6 * * 0-6', () ->
    sendWeather('[ここにchannel_id]')
  ).start()
未だにCoffeeScriptの書き方がよく理解できていない(¦3 _ )=


[…] 昨日紹介したコードでURLパラメータの指定方法に対して納得していなかったので 「querystring」を利用して修正してみました。 ※実行結果としては昨日のコードと同じです。 […]