blib/lib/Morris/Plugin/Dictionary.pm untested

filter: Statementstmt 0.0% 0 / 54 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 3 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 73 CC 6 SCAR 34.7
CC
6
Cov
0%
handle_message
42.0
BEGIN
2.0
BEGIN
2.0
CRAP 32.0
1 package Morris::Plugin::Dictionary;
2 use Moose;
3 use namespace::clean -except => qw(meta);
4  
5 extends 'Morris::Plugin';
6 with 'Morris::Plugin::WithDB';
7  
8 has max_definitions => (
9 is => 'ro',
10 isa => 'Int',
11 default => 10,
12 );
13  
14 after setup_dbh => sub {
15 my ($self, $dbh) = @_;
16 $dbh->exec(<<EOSQL, \&Morris::_noop_cb);
17 CREATE TABLE IF NOT EXISTS dictionary (
18 term TEXT NOT NULL,
19 definition TEXT NOT NULL,
20 UNIQUE (term, definition)
21 );
22 EOSQL
23 $dbh->commit;
24 };
25  
26 after register => sub {
27 my ($self, $conn) = @_;
28 $conn->register_hook( 'chat.privmsg', sub { $self->handle_message(@_) } );
29 };
30  
31 sub handle_message {
32 my ($self, $msg) = @_;
33  
34 my $message = $msg->message;
35 my $channel = $msg->channel;
36 my $nickname = $self->connection->nickname;
37 # <nickname>: XXX=YYYY
38 # <nickname>: XXX is YYYY
39  
40 # This is to learn new words
41 if ($message =~ /^$nickname:\s*([^=]+)\s*=\s*(.+)$/ ||
42 $message =~ /^$nickname:\s*(\S+)\s+is\s+(.+)$/
43 ) {
44 my ($term, $definition) = ($1, $2);
45 my $dbh = $self->get_dbh();
46 $dbh->exec(
47 "SELECT count(*) FROM dictionary WHERE term = ?",
48 $term,
49 sub {
50 my ($dbh, $rows, $rv) = @_;
51  
52 my $count = $rows->[0]->[0];
53 if ($count > $self->max_definitions) {
54 $self->connection->irc_privmsg({
55 channel => $channel,
56 message => "$term について詰め込みすぎです><。これ以上覚えられません!"
57 });
58 } else {
59 $dbh->exec(
60 "INSERT INTO dictionary (term, definition) VALUES (?, ?)",
61 $term,
62 $definition,
63 sub {
64 my @messages = ("らじゃ!", "あいよ!", "はいよー", "うーっす");
65 $self->connection->irc_privmsg({
66 channel => $channel,
67 message => $messages[ rand @messages ]
68 });
69 }
70 );
71 }
72 }
73 )
74 } elsif ( $message =~ /^$nickname:\s*([^?]+)\?$/) {
75 my $term = $1;
76 my $definition;
77  
78 my $dbh = $self->get_dbh();
79 $dbh->exec(
80 "SELECT definition FROM dictionary WHERE term = ?",
81 $term,
82 sub {
83 my ($dbh, $rows, $rv) = @_;
84  
85 my @definitions = map { $_->[0] } @$rows;
86 my $reply;
87 if (! @definitions) {
88 $reply = "$term ってなんですか?おいしい?";
89 } else {
90 $reply = "$term は ";
91 if (@definitions == 1) {
92 $reply .= $definitions[0];
93 } else {
94 my $last = pop @definitions;
95 $reply .= join(" 、", @definitions);
96 $reply .= " 、もしくは $last";
97 }
98 $reply .= " ということらしいですYO";
99 }
100
101 $self->connection->irc_privmsg({
102 channel => $channel,
103 message => $reply,
104 });
105 }
106 );
107 }
108 }
109  
110 __PACKAGE__->meta->make_immutable();
111  
112 1;