asjon/scripts/meteo.coffee

73 lines
2.0 KiB
CoffeeScript
Raw Permalink Normal View History

2015-04-25 18:37:13 +02:00
# Description:
# utilità per il meteo
#
# Dependencies:
2015-04-25 18:58:11 +02:00
# "moment":"2.10.2"
2015-04-25 18:37:13 +02:00
#
# Configuration:
# WEATHER_API_KEY
2015-04-25 18:37:13 +02:00
#
# Commands:
# hubot meteo/che tempo fa/c'è a <luogo>? - ottieni il meteo
2015-04-25 18:37:13 +02:00
#
# Author:
# Enrico Fasoli (fazo96)
# Michele Guerini Rocco (rnhmjoj)
2015-04-25 18:37:13 +02:00
2015-04-25 18:58:11 +02:00
moment = require 'moment'
regex = /(?:(?:d(?:a|i)mmi il )?meteo(?: per (.+))?|che tempo (?:fa|c'è)(?: (?:a|in) (.+))?)\??$/i
url1 = 'http://ip-api.com/json/'
url2 = 'http://api.openweathermap.org/data/2.5/weather?lang=it&units=metric'
err1 = 'non so dove sono: chiedimi un posto in particolare'
err2 = 'errore nel guardare il cielo'
2015-04-25 18:37:13 +02:00
module.exports = (robot) ->
get_location = (callback) ->
robot.http(url1).get() (err, r, body) ->
try
city = JSON.parse(body).city
catch e
# Fallback
callback 'Crema'
return
if err or !city? or city is undefined
# Fallback
callback 'Crema'
return
callback city
get_weather = (query, callback) ->
key = process.env.WEATHER_API_KEY
if not key
return callback 'non ho la chiave per openweathermap :('
robot.http(url2 + '&appid='+key + '&q='+query).get() (err, r, body) ->
callback err, body
send_weather = (res) -> (err, body) ->
2016-03-19 16:09:25 +01:00
return res.send "#{err2}:\n#{err}" if err
try
body = JSON.parse body
catch e
return res.send "#{err2}: #{e}"
unless body?.sys? and body?.main? and body?.weather?.push?
return res.send "#{err2}:\n#{JSON.stringify body}"
dawn = (moment.unix body.sys.sunrise).format 'H:MM'
dusk = (moment.unix body.sys.sunset ).format 'H:MM'
res.send "meteo per #{body.name}:\n
#{Math.round body.main.temp} °C, #{body.weather[0].description} con
#{body.main.humidity}% di umidità. l'alba è alle #{dawn} mentre il
tramonto alle #{dusk}"
robot.respond regex, (res) ->
city = res.match[1] || res.match[2]
if city?
get_weather city, send_weather res
else
get_location (location) ->
get_weather location, send_weather res