]> git.donarmstrong.com Git - infobot.git/blob - src/Modules/translate.pl
translate
[infobot.git] / src / Modules / translate.pl
1 # This program is distributed under the same terms as infobot.
2 # hacked by Tim@Rikers.org
3
4 package translate;
5 use strict;
6 use Data::Dumper;
7
8 my $no_translate;
9 my $url = 'http://translate.google.com/translate_a/t';
10
11 BEGIN {
12         eval "use URI::Escape"; # utility functions for encoding the
13         if ($@) { $no_translate++ }
14         eval "use LWP::UserAgent";
15         if ($@) { $no_translate++ }
16         eval "use JSON";
17         if ($@) { $no_translate++ }
18 }
19
20 sub translateParam {
21         return '' if $no_translate;
22         my ( $from, $to, $phrase ) = @_;
23         &::DEBUG("translate($from, $to, $phrase)");
24
25         my $ua = new LWP::UserAgent;
26         $ua->proxy( 'http', $::param{'httpProxy'} ) if ( &::IsParam('httpProxy') );
27
28         # Let's pretend
29         $ua->agent( "Mozilla/5.0 " . $ua->agent );
30         $ua->timeout(5);
31
32         my $req = HTTP::Request->new('GET', 'http://translate.google.com/translate_a/t?client=t&&sl='.$from.'&tl='.$to.'&text='.$phrase);
33
34         $req->header('Accept-Language' => 'en-us');
35         $req->header('Accept-Charset' => 'UTF-8,*');
36         my $json = JSON->new->utf8;
37         my $json_text=$ua->request($req)->content;
38         $json_text =~ s/,,/,"",/g;
39         $json_text =~ s/,,/,"",/g;
40         #&::DEBUG($json_text);
41         my @decoded_json = from_json($json_text);
42
43         return $decoded_json[0][0][0][0];
44 }
45
46 sub translate {
47         my ($message) = @_;
48         if ($message =~ m{(\S*)\s+(\S*)\s+(.+)}xoi) {
49                 &::performStrictReply( &translateParam( lc $1, lc $2, lc $3 ) );
50         }
51         return;
52 }
53
54 1;
55
56 # vim:ts=4:sw=4:expandtab:tw=80