]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/fish.rb
Plugin header boilerplating.
[user/henk/code/ruby/rbot.git] / data / 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     lines = Array.new
40     resp.body.each_line do |l|
41       lines.push l
42     end
43
44     l = lines.join(" ")
45     debug "babelfish response: #{l}"
46
47     if(l =~ /^\s+<td bgcolor=white class=s><div style=padding:10px;>(.*)<\/div>/)
48       answer = $1
49       # cache the answer
50       if(answer.length > 0)
51         @registry["#{trans_pair}/#{data_text}"] = answer
52       end
53       m.reply answer
54       return
55     end
56     m.reply "couldn't parse babelfish response html :("
57   else
58     m.reply "couldn't talk to babelfish :("
59   end
60   }
61   end
62 end
63 plugin = BabelPlugin.new
64 plugin.map 'translate to :tolang *phrase'
65 plugin.map 'translate from :fromlang *phrase'
66 plugin.map 'translate :fromlang :tolang *phrase'
67