4 # :title: Weather plugin for rbot
6 # Author:: MrChucho (mrchucho@mrchucho.net): NOAA National Weather Service support
7 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
9 # Copyright:: (C) 2006 Ralph M. Churchill
10 # Copyright:: (C) 2006-2007 Giuseppe Bilotta
14 require 'rexml/document'
16 # Wraps NOAA National Weather Service information
17 class CurrentConditions
18 def initialize(station, bot)
21 @url = "http://www.nws.noaa.gov/data/current_obs/#{URI.encode @station.upcase}.xml"
22 @current_conditions = String.new
26 resp = @bot.httputil.get_response(@url)
29 cc_doc = (REXML::Document.new resp.body).root
30 @current_conditions = parse(cc_doc)
32 raise Net::HTTPError.new(_("couldn't get data for %{station} (%{message})") % {
33 :station => @station, :message => resp.message
37 if Net::HTTPError === e
41 raise "error retrieving data: #{e}"
48 cc_doc.elements.each do |c|
49 cc[c.name.to_sym] = c.text
51 cc[:time] = cc[:observation_time_rfc822]
52 cc[:wind] = cc[:wind_string]
53 cc[:temperature] = cc[:temperature_string]
54 cc[:heatindexorwindchill] = heat_index_or_wind_chill(cc)
55 cc[:pressure] = cc[:pressure_string]
57 _("At %{time} the conditions at %{location} (%{station_id}) were %{weather} with a visibility of %{visibility_mi}mi. The wind was %{wind} with %{relative_humidity}%% relative humidity. The temperature was %{temperature}%{heatindexorwindchill}, and the pressure was %{pressure}.") % cc
60 def heat_index_or_wind_chill(cc)
61 hi = cc[:heat_index_string]
62 wc = cc[:windchill_string]
63 if hi and hi != 'NA' then
64 _(" with a heat index of %{hi}") % { :hi => hi }
65 elsif wc and wc != 'NA' then
66 _(" with a windchill of %{wc}") % { :wc => wc }
73 class WeatherPlugin < Plugin
75 Config.register Config::BooleanValue.new('weather.advisory',
77 :desc => "Should the bot report special weather advisories when any is present?")
78 Config.register Config::EnumValue.new('weather.units',
79 :values => ['metric', 'english', 'both'],
81 :desc => "Units to be used by default in Weather Underground reports")
84 def help(plugin, topic="")
87 "weather nws <station> => display the current conditions at the location specified by the NOAA National Weather Service station code <station> ( lookup your station code at http://www.nws.noaa.gov/data/current_obs/ )"
89 "weather [<units>] <location> => display the current conditions at the location specified, looking it up on the Weather Underground site; you can use 'station <code>' to look up data by station code ( lookup your station code at http://www.weatherunderground.com/ ); you can optionally set <units> to 'metric' or 'english' if you only want data with the units; use 'both' for units to go back to having both."
91 "weather information lookup. Looks up weather information for the last location you specified. See topics 'nws' and 'wu' for more information"
100 @wu_url = "http://mobile.wunderground.com/cgi-bin/findweather/getForecast?brand=mobile%s&query=%s"
101 @wu_station_url = "http://mobile.wunderground.com/auto/mobile%s/global/stations/%s.html"
104 def weather(m, params)
105 where = params[:where].to_s
106 service = params[:service].to_sym rescue nil
107 units = params[:units]
109 if where.empty? or !service or !units and @registry.has_key?(m.sourcenick)
110 reg = @registry[m.sourcenick]
111 debug "loaded weather info #{reg.inspect} for #{m.sourcenick}"
112 service = reg.first.to_sym if !service
113 where = reg[1].to_s if where.empty?
114 units = reg[2] rescue nil
118 if where.sub!(/^station\s+/,'')
126 debug "No weather location found for #{m.sourcenick}"
127 m.reply "I don't know where you are yet, #{m.sourcenick}. See 'help weather nws' or 'help weather wu' for additional help"
131 wu_units = String.new
133 units = @bot.config['weather.units'] unless units
136 when :english, :metric
137 wu_units = "_#{units}"
140 m.reply "Ignoring unknown units #{units}"
145 nws_describe(m, where)
147 wu_station(m, where, wu_units)
149 wu_weather(m, where, wu_units)
151 google_weather(m, where)
153 m.reply "I don't know the weather service #{service}, sorry"
157 @registry[m.sourcenick] = [service, where, units]
160 def nws_describe(m, where)
161 if @nws_cache.has_key?(where) then
162 met = @nws_cache[where]
164 met = CurrentConditions.new(where, @bot)
169 @nws_cache[where] = met
170 rescue Net::HTTPError => e
171 m.reply _("%{error}, will try WU service") % { :error => e.message }
177 m.reply "couldn't find weather data for #{where}"
181 def wu_station(m, where, units="")
183 xml = @bot.httputil.get(@wu_station_url % [units, CGI.escape(where)])
186 m.reply "couldn't retrieve weather information, sorry"
188 when /Search not found:/
189 m.reply "no such station found (#{where})"
191 when /<table border.*?>(.*?)<\/table>/m
193 m.reply wu_weather_filter(data)
194 wu_out_special(m, xml)
197 m.reply "something went wrong with the data for #{where}..."
200 m.reply "retrieving info about '#{where}' failed (#{e})"
204 def wu_weather(m, where, units="")
206 xml = @bot.httputil.get(@wu_url % [units, CGI.escape(where)])
209 m.reply "couldn't retrieve weather information, sorry"
210 when /City Not Found/
211 m.reply "no such location found (#{where})"
214 xml.scan(/<table border.*?>(.*?)<\/table>/m).each do |match|
215 data += wu_weather_filter(match.first)
220 m.reply "couldn't parse weather data from #{where}"
222 wu_out_special(m, xml)
223 when /<a href="\/auto\/mobile[^\/]+\/(?:global\/stations|[A-Z][A-Z])\//
224 wu_weather_multi(m, xml)
227 m.reply "something went wrong with the data from #{where}..."
230 m.reply "retrieving info about '#{where}' failed (#{e})"
234 def wu_weather_multi(m, xml)
236 stations = xml.scan(/<td>\s*(?:<a href="([^?"]+\?feature=[^"]+)"\s*[^>]*><img [^>]+><\/a>\s*)?<a href="\/auto\/mobile[^\/]+\/(?:global\/stations|([A-Z][A-Z]))\/([^"]*?)\.html">(.*?)<\/a>\s*:\s*(.*?)<\/td>/m)
238 m.reply "multiple stations available, use 'weather station <code>' or 'weather <city, state>' as appropriate, for one of the following (current temp shown):"
245 if state # US station
246 (warning ? "*" : "") + ("%s, %s (%s): %s" % [loc, state, par, w.ircify_html])
247 else # non-US station
248 (warning ? "*" : "") + ("station %s (%s): %s" % [loc, par, w.ircify_html])
251 m.reply stations.join("; ")
254 def wu_check_special(xml)
256 # We only scan the first half to prevent getting the advisories twice
257 xml[0,xml.length/2].scan(%r{<a href="([^"]+\?[^"]*feature=warning#([^"]+))"[^>]*>([^<]+)</a>}) do
259 :url => "http://mobile.wunderground.com"+$1,
263 spec_rx = Regexp.new("<a name=\"#{special[:type]}\">(?:.+?)<td align=\"left\">\\s+(.+?)\\s+</td>\\s+</tr>\\s+</table>", Regexp::MULTILINE)
264 spec_xml = @bot.httputil.get(special[:url])
265 if spec_xml and spec_td = spec_xml.match(spec_rx)
266 special.merge!(:text => spec_td.captures.first.ircify_html)
273 def wu_out_special(m, xml)
274 return unless @bot.config['weather.advisory']
275 specials = wu_check_special(xml)
277 specials.each do |special|
278 special.merge!(:underline => Underline)
280 m.reply("%{underline}%{special}%{underline}: %{text}" % special)
282 m.reply("%{underline}%{special}%{underline} @ %{url}" % special)
287 def wu_weather_filter(stuff)
289 if stuff.match(/<\/a>\s*Updated:\s*(.*?)\s*Observed at\s*(.*?)\s*<\/td>/)
290 result << ("Weather info for %s (updated on %s)" % [$2.ircify_html, $1.ircify_html])
292 stuff.scan(/<tr>\s*<td>\s*(.*?)\s*<\/td>\s*<td>\s*(.*?)\s*<\/td>\s*<\/tr>/m) { |k, v|
296 next if ["-", "- approx.", "N/A", "N/A approx."].include?(vv)
297 next if kk == "Raw METAR"
298 result << ("%s: %s" % [kk, vv])
300 return result.join('; ')
303 # TODO allow units choice other than lang, find how the API does it
304 def google_weather(m, where)
305 botlang = @bot.config['core.language'].intern
306 if Language::Lang2Locale.key?(botlang)
307 lang = Language::Lang2Locale[botlang].sub(/.UTF.?8$/,'')
309 lang = botlang.to_s[0,2]
312 debug "Google weather with language #{lang}"
313 xml = @bot.httputil.get("http://www.google.com/ig/api?hl=#{lang}&weather=#{CGI.escape where}")
315 weather = REXML::Document.new(xml).root.elements["weather"]
317 error = weather.elements["problem_cause"]
319 ermsg = error.attributes["data"]
320 ermsg = _("no reason specified") if ermsg.empty?
323 city = weather.elements["forecast_information/city"].attributes["data"]
324 date = Time.parse(weather.elements["forecast_information/current_date_time"].attributes["data"])
325 units = weather.elements["forecast_information/unit_system"].attributes["data"].intern
326 current_conditions = weather.elements["current_conditions"]
327 foreconds = weather.elements.to_a("forecast_conditions")
330 current_conditions.each { |el|
331 name = el.name.intern
332 value = el.attributes["data"].dup
348 foreconds.each { |forecast|
351 name = el.name.intern
352 value = el.attributes["data"]
357 value << (units == :SI ? "°C" : "°F")
358 value << " |" if name == :low
364 forecasts << cond.join(' ')
367 m.reply _("Google weather info for %{city} on %{date}: %{conds}. Three-day forecast: %{forecast}") % {
370 :conds => conds.join(', '),
371 :forecast => forecasts.join('; ')
375 m.reply _("Google weather failed: %{e}") % { :e => e}
382 plugin = WeatherPlugin.new
383 plugin.map 'weather :units :service *where',
390 :units => /metric|english|both/,
391 :service => /wu|nws|station|google/