switch the fish plugin to use the new map mechanism
[rbot] / rbot / plugins / fish.rb
1 require 'net/http'
2 require 'uri/common'
3 Net::HTTP.version_1_2
4
5 class BabelPlugin < Plugin
6   def help(plugin, topic="")
7     "translate to <lang> <string> => translate from english to <lang>, translate from <lang> <string> => translate to english from <lang>, translate <fromlang> <tolang> <string> => translate from <fromlang> to <tolang>. Languages: en, fr, de, it, pt, es, nl"
8   end
9   def translate(m, params)
10     langs = ["en", "fr", "de", "it", "pt", "es", "nl"]
11     trans_from = params[:fromlang] ? params[:fromlang] : 'en'
12     trans_to = params[:tolang] ? params[:tolang] : 'en'
13     trans_text = params[:phrase].to_s
14     
15     query = "/babelfish/tr"
16     lang_match = langs.join("|")
17     unless(trans_from =~ /^(#{lang_match})$/ && trans_to =~ /^(#{lang_match})$/)
18       m.reply "invalid language: valid languagess are: #{langs.join(' ')}"
19       return
20     end
21
22     data_text = URI.escape trans_text
23     trans_pair = "#{trans_from}_#{trans_to}"
24     data = "lp=#{trans_pair}&doit=done&intl=1&tt=urltext&urltext=#{data_text}"
25
26     # check cache for previous lookups
27     if @registry.has_key?("#{trans_pair}/#{data_text}")
28       m.reply @registry["#{trans_pair}/#{data_text}"]
29       return
30     end
31
32     http = @bot.httputil.get_proxy(URI.parse("http://babelfish.altavista.com"))
33
34     http.start {|http|
35       resp = http.post(query, data, {"content-type",
36       "application/x-www-form-urlencoded"})
37   
38   if (resp.code == "200")
39     resp.body.each_line do |l|
40       if(l =~ /^\s+<td bgcolor=white class=s><div style=padding:10px;>(.*)<\/div>/)
41         answer = $1
42         # cache the answer
43         if(answer.length > 0)
44           @registry["#{trans_pair}/#{data_text}"] = answer
45         end
46         m.reply answer
47         return
48       end
49     end
50     m.reply "couldn't parse babelfish response html :("
51   else
52     m.reply "couldn't talk to babelfish :("
53   end
54   }
55   end
56 end
57 plugin = BabelPlugin.new
58 plugin.map 'translate to :tolang *phrase'
59 plugin.map 'translate from :fromlang *phrase'
60 plugin.map 'translate :fromlang :tolang *phrase'
61