App-RoboBot
view release on metacpan or search on metacpan
lib/App/RoboBot/Plugin/API/Translate.pm view on Meta::CPAN
$message->response->raise('Translate to the same language? What is the point in that?');
return;
}
my $text = join(' ', @args);
unless (defined $text && length($text) > 1) {
$message->response->raise('Must provide text to translate.');
return;
}
my $equilibrium = $text;
my %seen = ( $from => { $text => 1 }, $to => {} );
# Cap attempts to find equilibrium at 6 round-trips between $from->$to->$from
for my $attempt (1..6) {
my $translation = $self->_do_translate($from, $to, $equilibrium);
last unless defined $translation;
last if exists $seen{$to}{$translation};
$seen{$to}{$translation} = 1;
$translation = $self->_do_translate($to, $from, $translation);
last unless defined $translation;
last if exists $seen{$from}{$translation};
$seen{$from}{$translation} = 1;
$equilibrium = $translation;
}
if (!defined $equilibrium || length($equilibrium) < 1 || $equilibrium eq $text) {
$message->response->raise('Could not get a party going with that phrase. Try again.');
return;
}
return $equilibrium;
}
sub _do_translate {
my ($self, $from, $to, $text) = @_;
$from = lc($from);
$to = lc($to);
my $key = lc($text);
return $self->cache->{$from}{$to}{$key}
if exists $self->cache->{$from}{$to}{$key};
return unless $self->update_token;
my $uri = URI->new;
$uri->scheme('http');
$uri->host('api.microsofttranslator.com');
$uri->path('/v2/Http.svc/Translate');
$uri->query_form({
from => $from,
to => $to,
text => $text,
});
my $req = HTTP::Request->new( GET => $uri->as_string );
$req->header('Authorization' => sprintf('Bearer %s', $self->token));
my $res = $self->ua->request($req);
return unless $res->is_success;
my $translation;
eval {
$translation = XML::LibXML->load_xml(
string => $res->decoded_content
)->getElementsByTagName("string") . "";
};
return if $@ || !defined $translation || length($translation) < 1;
# TODO: This should eventually have some sort of garbage collection to keep
# the translation cache from growing out of control on long running
# bot processes.
$self->cache->{$from}{$to}{$key} = $translation;
return $translation;
}
__PACKAGE__->meta->make_immutable;
1;
( run in 0.722 second using v1.01-cache-2.11-cpan-39bf76dae61 )