]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/fish.rb
d7dda52b9298610f3f49e5476ebafd42f5753a6b
[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   LANGS = %w{en fr de it pt es nl ru zh zt el ja ko}
7   def help(plugin, topic="")
8     "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: #{LANGS.join(', ')}"
9   end
10   def translate(m, params)
11     langs = LANGS
12     trans_from = params[:fromlang] ? params[:fromlang] : 'en'
13     trans_to = params[:tolang] ? params[:tolang] : 'en'
14     trans_text = params[:phrase].to_s
15     
16     query = "/babelfish/tr"
17     lang_match = langs.join("|")
18     unless(trans_from =~ /^(#{lang_match})$/ && trans_to =~ /^(#{lang_match})$/)
19       m.reply "invalid language: valid languagess are: #{langs.join(' ')}"
20       return
21     end
22
23     data_text = URI.escape trans_text
24     trans_pair = "#{trans_from}_#{trans_to}"
25     data = "lp=#{trans_pair}&doit=done&intl=1&tt=urltext&urltext=#{data_text}"
26
27     # check cache for previous lookups
28     if @registry.has_key?("#{trans_pair}/#{data_text}")
29       m.reply @registry["#{trans_pair}/#{data_text}"]
30       return
31     end
32
33     headers = {
34       "content-type" => "application/x-www-form-urlencoded; charset=utf-8"
35     }
36
37     begin
38       resp = @bot.httputil.get_response('http://babelfish.altavista.com'+query,
39                                         :method => :post,
40                                         :body => data,
41                                         :headers => headers)
42     rescue Exception => e
43       m.reply "http error: #{e.message}"
44       return
45     end
46
47     if (resp.code == "200")
48       lines = Array.new
49       resp.body.each_line { |l| lines.push l }
50
51       l = lines.join(" ")
52       debug "babelfish response: #{l}"
53
54       if(l =~ /^\s+<td bgcolor=white class=s><div style=padding:10px;>(.*)<\/div>/)
55         answer = $1
56         # cache the answer
57         if(answer.length > 0)
58           @registry["#{trans_pair}/#{data_text}"] = answer
59         end
60         m.reply answer
61         return
62       end
63       m.reply "couldn't parse babelfish response html :("
64     else
65       m.reply "couldn't talk to babelfish :("
66     end
67   end
68 end
69 plugin = BabelPlugin.new
70 plugin.map 'translate to :tolang *phrase'
71 plugin.map 'translate from :fromlang *phrase'
72 plugin.map 'translate :fromlang :tolang *phrase'
73