|
| 1 | +require 'sinatra' |
| 2 | +require 'rubygems' |
| 3 | +require 'twilio-ruby' |
| 4 | +require 'httparty' |
| 5 | +require 'active_support' |
| 6 | +require 'active_support/core_ext' |
| 7 | + |
| 8 | +get '/' do |
| 9 | + @@body = params[:Body] |
| 10 | + redirect to('/g_weather') |
| 11 | +end |
| 12 | + |
| 13 | +get '/g_weather' do |
| 14 | + # google geocoordinates API |
| 15 | + weather_search = @@body.gsub(" ", "+") |
| 16 | + google_api_response = HTTParty.get("https://maps.googleapis.com/maps/api/geocode/json?address=#{weather_search}") |
| 17 | + if google_api_response['status'] != "OK" |
| 18 | + @@error_msg = "Google request didn't work." |
| 19 | + redirect to('/not_right') |
| 20 | + end |
| 21 | + |
| 22 | + # forecast_io API |
| 23 | + city_lat = google_api_response["results"][0]["geometry"]["location"]["lat"] |
| 24 | + city_lng = google_api_response["results"][0]["geometry"]["location"]["lng"] |
| 25 | + forecast_io_response = HTTParty.get("https://api.forecast.io/forecast/#{ENV['FORECAST_IO_KEY']}/#{city_lat},#{city_lng}") |
| 26 | + if not forecast_io_response['error'].nil? |
| 27 | + @@error_msg = "Forecast.io request didn't work." |
| 28 | + redirect to('/not_right') |
| 29 | + end |
| 30 | + |
| 31 | + # all okay from APIs, get the weather info |
| 32 | + today_summary = forecast_io_response["daily"]["data"][0]["summary"] |
| 33 | + current_temp = forecast_io_response["currently"]["apparentTemperature"].round |
| 34 | + today_max = forecast_io_response["daily"]["data"][0]["apparentTemperatureMax"].round |
| 35 | + today_min = forecast_io_response["daily"]["data"][0]["apparentTemperatureMin"].round |
| 36 | + today_max_time = Time.at(forecast_io_response["daily"]["data"][0]["apparentTemperatureMaxTime"]).in_time_zone("America/Denver").strftime("%-l %p %Z") |
| 37 | + today_min_time = Time.at(forecast_io_response["daily"]["data"][0]["apparentTemperatureMinTime"]).in_time_zone("America/Denver").strftime("%-l %p %Z") |
| 38 | + |
| 39 | + # send weather text back |
| 40 | + message = "\n#{@@body}: #{today_summary}\nHigh of #{today_max}˚F at #{today_max_time}.\nLow of #{today_min}˚F at #{today_min_time}.\nNow: #{current_temp}˚F." |
| 41 | + twiml = Twilio::TwiML::Response.new do |r| |
| 42 | + r.Message message |
| 43 | + end |
| 44 | + twiml.text |
| 45 | +end |
| 46 | + |
| 47 | +# send error msg |
| 48 | +get '/not_right' do |
| 49 | + twiml = Twilio::TwiML::Response.new do |r| |
| 50 | + r.Message @@error_msg |
| 51 | + end |
| 52 | + twiml.text |
| 53 | +end |
0 commit comments