| 1 | # $Id$ |
|---|
| 2 | |
|---|
| 3 | package Morris::Plugin::Channel::Reputation; |
|---|
| 4 | use Moose; |
|---|
| 5 | use DBI; |
|---|
| 6 | |
|---|
| 7 | with 'Morris::Plugin'; |
|---|
| 8 | |
|---|
| 9 | __PACKAGE__->meta->make_immutable; |
|---|
| 10 | |
|---|
| 11 | no Moose; |
|---|
| 12 | |
|---|
| 13 | sub register { |
|---|
| 14 | my ($self, $conn) = @_; |
|---|
| 15 | $conn->register_hook( 'channel.public', sub { $self->handle_message(@_) } ); |
|---|
| 16 | } |
|---|
| 17 | |
|---|
| 18 | sub handle_message { |
|---|
| 19 | my ($self, $args) = @_; |
|---|
| 20 | |
|---|
| 21 | my $channel = $args->{message}->channel; |
|---|
| 22 | my $message = $args->{message}->message; |
|---|
| 23 | my $dbh; |
|---|
| 24 | |
|---|
| 25 | while ( $message =~ m{([\w_-]+)(--|\+\+)}g ) { |
|---|
| 26 | my $who = $1; |
|---|
| 27 | my $action = $2; |
|---|
| 28 | my $add = $action eq '--' ? -1 : 1; |
|---|
| 29 | my ($pluses, $minuses, $score) = (0, 0, 0); |
|---|
| 30 | |
|---|
| 31 | $dbh ||= $self->get_dbh(); |
|---|
| 32 | |
|---|
| 33 | my $sth = $dbh->prepare("SELECT score, pluses, minuses FROM reputation WHERE nickname = ?"); |
|---|
| 34 | my $rv; |
|---|
| 35 | if ( ($rv = $sth->execute($who)) > 0) { |
|---|
| 36 | ($pluses, $minuses, $score) = $sth->fetchrow_array(); |
|---|
| 37 | } |
|---|
| 38 | $sth->finish; |
|---|
| 39 | |
|---|
| 40 | if ($rv > 0) { |
|---|
| 41 | $dbh->do("UPDATE reputation SET score = score + ?, pluses = pluses + ?, minuses = minuses + ? WHERE nickname = ?", undef, $add, $add > 0 ? (1, 0) : (0, 1), $who); |
|---|
| 42 | } else { |
|---|
| 43 | $dbh->do("INSERT INTO reputation (score, pluses, minuses, nickname) VALUES( ?, ? )", undef, $add, $add > 0 ? (1, 0) : (0, 1), $who); |
|---|
| 44 | } |
|---|
| 45 | |
|---|
| 46 | $self->connection->irc_notice({ |
|---|
| 47 | channel => $channel, |
|---|
| 48 | message => "$who: " . ($score + $add) . " ($pluses++, $minuses++)" |
|---|
| 49 | }); |
|---|
| 50 | } |
|---|
| 51 | } |
|---|
| 52 | |
|---|
| 53 | sub get_dbh { |
|---|
| 54 | my $dbh = DBI->connect('dbi:SQLite:dbname=/service/morris/reputation.db'); |
|---|
| 55 | |
|---|
| 56 | $dbh->do(<<EOSQL); |
|---|
| 57 | CRETE TABLE IF NOT EXISTS reputation ( |
|---|
| 58 | id INTEGER AUTO_INCREMENT PRIMARY KEY, |
|---|
| 59 | score INTEGER NOT NULL DEFAULT 0, |
|---|
| 60 | pluses INTEGER NOT NULL DEFAULT 0, |
|---|
| 61 | minuses INTEGER NOT NULL DEFAULT 0, |
|---|
| 62 | nickname TEXT NOT NULL, |
|---|
| 63 | UNIQUE KEY (nickname) |
|---|
| 64 | EOSQL |
|---|
| 65 | return $dbh; |
|---|
| 66 | } |
|---|
| 67 | |
|---|
| 68 | 1; |
|---|