Skip to content

Instantly share code, notes, and snippets.

@mbmccormick
Created November 3, 2011 03:40
Show Gist options
  • Save mbmccormick/1335716 to your computer and use it in GitHub Desktop.
Save mbmccormick/1335716 to your computer and use it in GitHub Desktop.
Update Weather script to support "natural language" replies, specify temperature format
robot.respond /weather(?: me|for|in)?\s(.*)/, (msg) ->
query msg, (body, err) ->
return msg.send err if err
city = body.getElementsByTagName("city")[0]
return msg.send "Sorry, but you didn't specify a location." if not city or not city.getAttribute
city = city.getAttribute("data")
currentCondition = body.getElementsByTagName("current_conditions")[0].getAttribute("data")
conditions = body.getElementsByTagName("current_conditions")[0].getElementsByTagName("condition")[0].getAttribute("data")
humidity = body.getElementsByTagName("current_conditions")[0].getElementsByTagName("humidity")[0].getAttribute("data").split(' ')[1]
if env.HUBOT_WEATHER_CELSIUS
temp = body.getElementsByTagName("current_conditions")[0].getElementsByTagName("temp_c")[0].getAttribute("data") + "ºC"
else
temp = body.getElementsByTagName("current_conditions")[0].getElementsByTagName("temp_f")[0].getAttribute("data") + "ºF"
msg.send "Currently in #{city} it is #{conditions} and #{temp} with a humidity of #{humidity}.\n"
getDom = (xml) ->
body = jsdom.jsdom(xml)
throw Error("No XML data returned.") if body.getElementsByTagName("weather")[0].childNodes.length == 0
body
convertTempToCelsius = (f) ->
((5 / 9) * (f - 32)).toFixed 0
query = (msg, cb) ->
location = msg.match[1]
msg.http("http://www.google.com/ig/api")
.query(weather: location)
.get() (err, res, body) ->
try
body = getDom body
catch err
err = "Could not fetch weather data."
cb(body, err)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment