root/lang/perl/Morris/trunk/lib/Morris/Plugin/Channel/Reputation.pm @ 31817

Revision 31817, 1.8 kB (checked in by daisuke, 6 years ago)

現実逃避

  • Property svn:keywords set to Id
Line 
1# $Id$
2
3package Morris::Plugin::Channel::Reputation;
4use Moose;
5use DBI;
6
7with 'Morris::Plugin';
8
9__PACKAGE__->meta->make_immutable;
10
11no Moose;
12
13sub register {
14    my ($self, $conn) = @_;
15    $conn->register_hook( 'channel.public', sub { $self->handle_message(@_) } );
16}
17
18sub 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
53sub get_dbh {
54    my $dbh = DBI->connect('dbi:SQLite:dbname=/service/morris/reputation.db');
55
56    $dbh->do(<<EOSQL);
57CRETE 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)
64EOSQL
65    return $dbh;
66}
67
681;
Note: See TracBrowser for help on using the browser.