| 1 | package Mojo::Weixin::Plugin::Translation; | ||
| 2 | use strict; | ||
| 3 | use Mojo::Util qw(url_escape md5_sum ); | ||
| 4 | our $PRIORITY = 93; | ||
| 5 | sub call { | ||
| 6 | my ($client,$data) = @_; | ||
| 7 | my $api = 'http://api.fanyi.baidu.com/api/trans/vip/translate'; | ||
| 8 | my $appid = $data->{appid} || '20160516000021158'; | ||
| 9 | my $appsecret = $data->{appsecret} || '2QoSmvMuun8btJmsl446'; | ||
| 10 | my $callback = sub{ | ||
| 11 | my($client,$msg) = @_; | ||
| 12 | return if not $msg->allow_plugin; | ||
| 13 | return if $msg->class eq "send" and $msg->from ne "api" and $msg->from ne "irc"; | ||
| 14 | if($msg->content =~ /^翻译\s+(.*)/s){ | ||
| 15 | my $query = $1; | ||
| 16 | return if not $query; | ||
| 17 | $msg->allow_plugin(0); | ||
| 18 | my $salt = time; | ||
| 19 | $client->http_get($api,{json=>1},form=>{ | ||
| 20 | q => $query, | ||
| 21 | from => 'auto', | ||
| 22 | to => 'auto', | ||
| 23 | appid => $appid, | ||
| 24 | salt => $salt, | ||
| 25 | sign => md5_sum($appid . $query . $salt . $appsecret), | ||
| 26 | },sub{ | ||
| 27 | my $json = shift; | ||
| 28 | if( not defined $json ){$msg->reply("翻译失败: api接口不可用")} | ||
| 29 | elsif(defined $json and exists $json->{error_code}){ | ||
| 30 | $msg->reply("翻译失败: api接口不可用(" . $json->{error_code} . " " . $json->{error_msg} . ")"); | ||
| 31 | } | ||
| 32 | elsif(defined $json){ | ||
| 33 | $msg->reply( join " ",map {$_->{dst}} @{ $json->{trans_result} } ); | ||
| 34 | } | ||
| 35 | }); | ||
| 36 | } | ||
| 37 | }; | ||
| 38 | $client->on(receive_message=>$callback,send_message=>$callback); | ||
| 39 | } | ||
| 40 | 1; |