1POE::Component::IRC::CoUoskebrooCko:n:tTrriabnuPstOleEad:t:oPCreo(rm3lp)oDnoecnutm:e:nItRaCt:i:oCnookbook::Translator(3)
2
3
4
6 POE::Component::IRC::Cookbook::Translator - A bot that can translate
7 text
8
10 This bot uses POE::Component::Lingua::Translate to translate text for
11 channel members. It makes use of the "BotCommand" plugin to handle the
12 translate command.
13
15 #!/usr/bin/env perl
16
17 use strict;
18 use warnings;
19 use Encode qw(decode);
20 use Encode::Guess;
21 use POE;
22 use POE::Component::IRC::Common qw(parse_user);
23 use POE::Component::IRC::State;
24 use POE::Component::IRC::Plugin::AutoJoin;
25 use POE::Component::IRC::Plugin::BotCommand;
26 use POE::Component::Lingua::Translate;
27
28 POE::Session->create(
29 package_states => [
30 main => [ qw(_start irc_botcmd_trans translated) ]
31 ],
32 heap => {
33 translators => { },
34 }
35 );
36
37 $poe_kernel->run();
38
39 sub _start {
40 my $heap = $_[HEAP];
41 my $irc = POE::Component::IRC::State->spawn(
42 Nick => 'translator_bot',
43 Server => 'irc.freenode.net',
44 );
45 $heap->{irc} = $irc;
46
47 $irc->plugin_add('AutoJoin', POE::Component::IRC::Plugin::AutoJoin->new(
48 Channels => [ '#test_channel1', '#test_channel2' ]
49 ));
50
51 $irc->plugin_add('BotCommand', POE::Component::IRC::Plugin::BotCommand->new(
52 Commands => {
53 trans => 'Usage: trans <from>,<to> <text>'
54 }
55 ));
56
57 $irc->yield(register => 'botcmd_trans');
58 $irc->yield('connect');
59 return;
60 }
61
62 sub irc_botcmd_trans {
63 my $heap = $_[HEAP];
64 my $irc = $heap->{irc};
65 my $nick = parse_user( $_[ARG0] );
66 my $channel = $_[ARG1];
67 my ($from, $to, $text) = split /,|\s+/, $_[ARG2], 3;
68
69 if (!exists $heap->{translators}->{$from . $to}) {
70 eval {
71 $heap->{translators}->{$from . $to} = POE::Component::Lingua::Translate->new(
72 alias => $from . $to,
73 back_end => 'Babelfish',
74 src => $from,
75 dest => $to,
76 );
77 };
78
79 if ($@) {
80 $irc->yield(privmsg => $channel, "$nick: There was an error: $@");
81 return;
82 }
83 }
84
85 $poe_kernel->post($from . $to => translate =>
86 to_utf8($text),
87 {
88 channel => $channel,
89 nick => $nick,
90 }
91 );
92 return;
93 }
94
95 # Some IRC users use CP1252, some use UTF-8. Let's decode it properly.
96 sub to_utf8 {
97 my ($line) = @_;
98 my $utf8 = guess_encoding($line, 'utf8');
99 return ref $utf8 ? decode('utf8', $line) : decode('cp1252', $line);
100 }
101
102 sub translated {
103 my $irc = $_[HEAP]->{irc};
104 my ($text, $context, $error) = @_[ARG0, ARG1, ARG2];
105
106 if ($error) {
107 $irc->yield(
108 'privmsg',
109 $context->{channel},
110 $context->{nick} . ": There was an error: $error",
111 );
112 return;
113 }
114
115 $irc->yield(
116 'privmsg',
117 $context->{channel},
118 $context->{nick} . ': ' . $text,
119 );
120 return;
121 }
122
124 Hinrik Oern Sigurd`sson, hinrik.sig@gmail.com
125
126
127
128perl v5.12.2 2P0O1E0:-:1C1o-m0p5onent::IRC::Cookbook::Translator(3)