]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - rbot/plugins/fish.rb
Wed Jul 20 23:30:01 BST 2005 Tom Gilbert <tom@linuxbrit.co.uk>
[user/henk/code/ruby/rbot.git] / 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 privmsg(m)
10
11     langs = ["en", "fr", "de", "it", "pt", "es", "nl"]
12
13     query = "/babelfish/tr"
14     if(m.params =~ /^to\s+(\S+)\s+(.*)/)
15       trans_from = "en"
16       trans_to = $1
17       trans_text = $2
18     elsif(m.params =~ /^from\s+(\S+)\s+(.*)/)
19       trans_from = $1
20       trans_to = "en"
21       trans_text = $2
22     elsif(m.params =~ /^(\S+)\s+(\S+)\s+(.*)/)
23       trans_from = $1
24       trans_to = $2
25       trans_text = $3
26     else
27       m.reply "incorrect usage: " + help(m.plugin)
28       return
29     end
30     lang_match = langs.join("|")
31     unless(trans_from =~ /^(#{lang_match})$/ && trans_to =~ /^(#{lang_match})$/)
32       m.reply "invalid language: valid languagess are: #{langs.join(' ')}"
33       return
34     end
35
36     data_text = URI.escape trans_text
37     trans_pair = "#{trans_from}_#{trans_to}"
38     data = "lp=#{trans_pair}&doit=done&intl=1&tt=urltext&urltext=#{data_text}"
39
40     # check cache for previous lookups
41     if @registry.has_key?("#{trans_pair}/#{data_text}")
42       m.reply @registry["#{trans_pair}/#{data_text}"]
43       return
44     end
45
46     http = @bot.httputil.get_proxy(URI.parse("http://babelfish.altavista.com"))
47
48     http.start {|http|
49       resp = http.post(query, data, {"content-type",
50       "application/x-www-form-urlencoded"})
51         
52         if (resp.code == "200")
53     #puts resp.body
54         resp.body.each_line {|l|
55                 if(l =~ /^\s+<td bgcolor=white class=s><div style=padding:10px;>(.*)<\/div>/)
56                         answer = $1
57                         # cache the answer
58                         if(answer.length > 0)
59                                 @registry["#{trans_pair}/#{data_text}"] = answer
60                         end
61                         m.reply answer
62                         return
63                 end
64         }
65                 m.reply "couldn't parse babelfish response html :("
66         else
67                 m.reply "couldn't talk to babelfish :("
68         end
69         }
70   end
71 end
72 plugin = BabelPlugin.new
73 plugin.register("translate")
74