| 1 | package Morris::Plugin::Reputation; | ||
| 2 | use Moose; | ||
| 3 | use namespace::clean -except => qw(meta); | ||
| 4 | |||
| 5 | extends 'Morris::Plugin'; | ||
| 6 | with 'Morris::Plugin::WithDB'; | ||
| 7 | |||
| 8 | after register => sub { | ||
| 9 | my ($self, $conn) = @_; | ||
| 10 | $conn->register_hook( 'chat.privmsg', sub { $self->handle_message(@_) } ); | ||
| 11 | }; | ||
| 12 | |||
| 13 | after setup_dbh => sub { | ||
| 14 | my ($self, $dbh) = @_; | ||
| 15 | $dbh->exec(<<EOSQL, \&Morris::_noop_cb); | ||
| 16 | CREATE TABLE IF NOT EXISTS reputation ( | ||
| 17 | id INTEGER AUTO_INCREMENT PRIMARY KEY, | ||
| 18 | score INTEGER NOT NULL DEFAULT 0, | ||
| 19 | pluses INTEGER NOT NULL DEFAULT 0, | ||
| 20 | minuses INTEGER NOT NULL DEFAULT 0, | ||
| 21 | nickname TEXT NOT NULL, | ||
| 22 | UNIQUE (nickname) | ||
| 23 | ); | ||
| 24 | EOSQL | ||
| 25 | $dbh->commit(\&Morris::_noop_cb); | ||
| 26 | }; | ||
| 27 | |||
| 28 | sub handle_message { | ||
| 29 | my ($self, $msg) = @_; | ||
| 30 | |||
| 31 | my $dbh = $self->get_dbh(); | ||
| 32 | my $channel = $msg->channel; | ||
| 33 | my $message = $msg->message; | ||
| 34 | |||
| 35 | while ( $message =~ m{(\S+)(--|\+\+)(?:\s+\*\s*(\d+))?}g ) { | ||
| 36 | my $who = $1; | ||
| 37 | my $action = $2; | ||
| 38 | my $add = ($action eq '--' ? -1 : 1) * ($3 || 1); | ||
| 39 | |||
| 40 | $dbh->exec( | ||
| 41 | "SELECT score, pluses, minuses FROM reputation WHERE nickname = ?", | ||
| 42 | $who, | ||
| 43 | sub { | ||
| 44 | my ($dbh, $rows, $rv) = @_; | ||
| 45 | my ($pluses, $minuses, $score) = (0, 0, 0); | ||
| 46 | my $update = 0; | ||
| 47 | if ($rv && scalar @$rows) { | ||
| 48 | $update = 1; | ||
| 49 | ($score, $pluses, $minuses) = @{ $rows->[0] }; | ||
| 50 | } | ||
| 51 | |||
| 52 | $score ||= 0; | ||
| 53 | $pluses ||= 0; | ||
| 54 | $minuses |= 0; | ||
| 55 | |||
| 56 | if ($add > 0) { | ||
| 57 | $score += $add; | ||
| 58 | $pluses += $add; | ||
| 59 | } else { | ||
| 60 | $score += $add; | ||
| 61 | $minuses += ($add * -1); | ||
| 62 | } | ||
| 63 | |||
| 64 | my @args = ($score, $pluses, $minuses, $who); | ||
| 65 | if ($update) { | ||
| 66 | $dbh->exec(<<EOSQL, @args, \&Morris::_noop_cb); | ||
| 67 | UPDATE reputation | ||
| 68 | SET score = ?, | ||
| 69 | pluses = ?, | ||
| 70 | minuses = ? | ||
| 71 | WHERE nickname = ? | ||
| 72 | EOSQL | ||
| 73 | } else { | ||
| 74 | $dbh->exec(<<EOSQL, @args, \&Morris::_noop_cb); | ||
| 75 | INSERT INTO reputation | ||
| 76 | (score, pluses, minuses, nickname) | ||
| 77 | VALUES( ?, ?, ?, ?) | ||
| 78 | EOSQL | ||
| 79 | } | ||
| 80 | $dbh->commit(\&Morris::_noop_cb); | ||
| 81 | |||
| 82 | $self->connection->irc_notice({ | ||
| 83 | channel => $channel, | ||
| 84 | message => "$who: $score (${pluses}++, ${minuses}--)" | ||
| 85 | }); | ||
| 86 | } | ||
| 87 | ); | ||
| 88 | } | ||
| 89 | } | ||
| 90 | |||
| 91 | __PACKAGE__->meta->make_immutable; | ||
| 92 | |||
| 93 | 1; |