Skip to content

Commit

Permalink
Fixed nicks, fixed kicks, added MUC roster functionality to Bot.pm
Browse files Browse the repository at this point in the history
  • Loading branch information
zhmylove committed Jan 13, 2016
1 parent ac68d3b commit 9691b31
Show file tree
Hide file tree
Showing 2 changed files with 183 additions and 88 deletions.
76 changes: 70 additions & 6 deletions patch/Bot.pm.patch
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
--- Bot.pm.old 2016-01-09 19:49:41.801668822 +0300
+++ Bot.pm 2016-01-10 04:10:33.630669276 +0300
+++ Bot.pm 2016-01-13 15:39:49.231884763 +0300
@@ -49,17 +49,18 @@
has 'loop_sleep_time' => (isa => PosNum, is => 'rw', default => 5);
has 'process_timeout' => (isa => PosNum, is => 'rw', default => 5);
Expand All @@ -22,7 +22,27 @@
has 'forum_join_time' => (isa => HashRef[Int], is => 'rw', default => sub{{}}); # List of when we joined each forum
has 'out_messages_per_second' => (isa => PosNum, is => 'rw', default => sub{5});
has 'message_delay' => (isa => PosNum, is => 'rw', default => sub {1/5});
@@ -422,7 +423,7 @@
@@ -67,6 +68,8 @@
has 'max_message_size' => (isa => HundredInt, is => 'rw', default => 1000000);
has 'max_messages_per_hour' => (isa => PosInt, is => 'rw', default => 1000000);

+has 'JidDB' => (isa => HashRef[HashRef[Str]], is => 'rw', required => 1);
+
# Initialize this hour's message count.
has 'messages_sent_today' => (isa => 'HashRef', is => 'ro', default => sub{{(localtime)[7] => {(localtime)[2] => 0}}});

@@ -294,6 +297,10 @@

safetey: 166

+=item B<JidDB>
+
+Database of JIDs per forum
+
=back

=cut
@@ -422,7 +429,7 @@
$self->Process(5);

foreach my $forum (keys %{$self->forums_and_responses}) {
Expand All @@ -31,7 +51,7 @@
}

INFO("Connected to server '" . $self->server . "' successfully");
@@ -443,12 +444,14 @@
@@ -443,12 +450,14 @@
sub JoinForum {
my $self = shift;
my $forum_name = shift;
Expand All @@ -46,7 +66,7 @@
);

$self->forum_join_time->{$forum_name} = time;
@@ -649,21 +652,7 @@
@@ -649,21 +658,7 @@

# Determine if this message was addressed to me. (groupchat only)
my $bot_address_from;
Expand All @@ -69,7 +89,28 @@

# Call the message callback if it's defined.
if( defined $self->message_function) {
@@ -896,7 +885,8 @@
@@ -789,6 +784,20 @@
my $status = $presence->GetStatus();
$status = "." if(!defined $status);

+ my ($forum, $nick) = split '/', $from;
+ $forum = (split '@', $forum)[0];
+
+ if($type eq 'unavailable') { # Delete disconnected user
+ if (defined ${ $self->JidDB->{$forum} }{$nick}) {
+ delete ${ $self->JidDB->{$forum} }{$nick};
+ }
+
+ return;
+ }
+
+ # "register" user on any other types
+ ${ $self->JidDB->{$forum} }{$nick} = 1;
+
DEBUG("Presence From $from t=$type s=$status");
DEBUG("Presence XML: " . $presence->GetXML());
}
@@ -896,7 +905,8 @@
Assures message size does not exceed a limit and chops it into pieces if need be.

NOTE: non-printable characters (unicode included) will be stripped before sending to the server via:
Expand All @@ -79,7 +120,7 @@

=cut

@@ -989,7 +979,8 @@
@@ -989,7 +999,8 @@

# Strip out anything that's not a printable character
# Now with unicode support?
Expand All @@ -89,3 +130,26 @@

my $message_length = length($message_chunk);
DEBUG("Sending message $yday-$hour-$messages_this_hour $message_length bytes to $recipient");
@@ -1134,6 +1145,22 @@
$self->jabber_client->Subscription(type=>"unsubscribe", to=>$user);
$self->jabber_client->Subscription(type=>"unsubscribed",to=>$user);
}
+
+=item B<IsInRoom>
+
+Returns 1 or 0 if nick is present at specified forum
+
+=cut
+
+sub IsInRoom {
+ my $self = shift;
+ my $forum = shift;
+ my $nick = shift;
+
+ return 0 if(!defined $forum || !defined $nick);
+
+ return ${ $self->JidDB->{$forum} }{$nick} || 0;
+}
=back

=head1 AUTHOR
195 changes: 113 additions & 82 deletions src/jplbot.pl
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,15 @@
my $col_count = int($minimum_colors + ($#colors - $minimum_colors + 1) * rand);
my %col_hash;
$col_hash{lc($_)} = 1 for @colors;
my %jid_DB = ();

my $qname = quotemeta($name);
my $bot_address = "https://github.com/tune-it/jplbot";
$SIG{INT} = \&shutdown;
$SIG{TERM} = \&shutdown;
binmode STDOUT, ':utf8';
my $bot_address = "https://github.com/tune-it/jplbot";
my $rb = "[\x{20}\x{22}\x{26}\x{27}\x{2f}\x{3a}\x{3c}\x{3e}\x{40}]";
my $rB = "[^$rb]";

sub shutdown {
store \%karma, $karmafile and say "Karma saved to: $karmafile";
Expand All @@ -68,6 +71,8 @@ sub bomb_user {
delete $bomb_resourse{lc($user)};
delete $bomb_nick{lc($user)};

return unless $bot->IsInRoom((split '@', $to)[0], $nick);

$bot->SendGroupMessage($to, "$nick: ты взорвался!");

my $xml = "<iq from='$username\@$server/$name' id='korg1' to='$to' " .
Expand All @@ -89,29 +94,26 @@ sub new_bot_message {
my %msg = @_;
my $bot = $msg{'bot_object'};

my $from = $msg{'from_full'};
$from =~ s{^.+/([^/]+)$}{$1};

my $resourse = $msg{'from_full'};
$resourse =~ s{^(.+)/[^/]+$}{$1};
my ($resource, $from) = split '/', $msg{'from_full'};
my $forum = (split '@', $resource)[0];

my $to_me = ($msg{'body'} =~ s{^$qname: }{});
if ($msg{'type'} eq "chat") {
$bot->SendPersonalMessage($msg{'reply_to'},
"Я не работаю в привате. Если Вы нашли проблему, у Вас есть предложения или " .
"пожелания, пишите issue на $bot_address");
"Я не работаю в привате. Если Вы нашли проблему, " .
"у Вас есть предложения или пожелания, пишите issue на $bot_address");
return;
}

given ($msg{'body'}) {

when (/^date\s*$/i) {
when (/^(?:date|дата)\s*$/i) {
$bot->SendGroupMessage($msg{'reply_to'},
"$from: " . localtime);
}

when (/^time\s*$/i) {
when (/^(?:time|время)\s*$/i) {
$bot->SendGroupMessage($msg{'reply_to'},
"$from: " . time);
}
Expand Down Expand Up @@ -145,94 +147,40 @@ sub new_bot_message {

when (/^help\s*$/i) {
$bot->SendGroupMessage($msg{'reply_to'},
"$from: пробуй так: bomb date fortune karma time");
"$from: я написал тебе в личку");

$bot->SendPersonalMessage($msg{'reply_to'} . "/$from",
"Краткая справка: \n" .
" bomb nick -- установить бомбу\n" .
" date -- вывести дату\n" .
" fortune -- вывеси цитату\n" .
" karma nick -- вывести карму\n" .
" sayto /nick/ -- сказать пользователю\n" .
" time -- вывести время\n" .
"\n" .
"Вопросы и предложения: $bot_address\n" .
"Чмоки ;-)"
);
}

when (/^fortune\s*$/i) {
when (/^(?:fortune|ф)\s*$/i) {
my $fortune = `/usr/games/fortune -s`;
chomp $fortune;
$bot->SendGroupMessage($msg{'reply_to'},
"$from: $fortune");
sleep 1;
}

when (/^karma\s*$/i) {
when (/^(?:karma|карма)\s*$/i) {
$bot->SendGroupMessage($msg{'reply_to'},
"$from: твоя карма: " . ($karma{lc($from)}||0));
}

when (/^karma\s*(\S+)$/i) {
$bot->SendGroupMessage($msg{'reply_to'},
"$from: карма $1: " . ($karma{lc($1)}||0));
}

when (/^bomb\s*$/i) {
when (/^(?:bomb|бомба)\s*$/i) {
$bot->SendGroupMessage($msg{'reply_to'},
"$from: бомба -- это не игрушки!");
}

when (/^bomb\s*(\S+)$/i) {
my $name = $1;

if ($from eq $name) {
$bot->SendGroupMessage($msg{'reply_to'},
"$from: привык забавляться сам с собой?");
return;
}

if (defined $bomb_time{lc($name)}) {
$bot->SendGroupMessage($msg{'reply_to'},
"$from: на $name уже установлена бомба.");
return;
}

if (abs(time - $last_bomb_time) < 180) {
$bot->SendGroupMessage($msg{'reply_to'},
"$from: у меня ещё не восполнен боезапас. Жди.");
return;
}

$last_bomb_time = time;

my %selected_colors;
while($col_count != keys %selected_colors){
$selected_colors{$colors[int($#colors * rand)]} = 1;
}

my $selected_colors_t = join ', ', (sort keys %selected_colors);

$selected_colors_t =~ s/,( \S+)$/ и$1/i;

$bomb_time{lc($name)} = time;
$bomb_correct{lc($name)} = (keys %selected_colors)[0];
$bomb_resourse{lc($name)} = $resourse;
$bomb_nick{lc($name)} = $name;

my $txt = "Привет от $from, $name! Я хочу сыграть с тобой в игру.\n" .
"Правила очень простые. Всю свою жизнь ты не уважал random, " .
"и теперь пришло время поплатиться. \n" .
"На тебе бомба, из которой торчат " .
"$selected_colors_t провода. \n" .
"Твоя задача -- правильно выбрать провод. " .
"До взрыва осталось 1-2 минуты. Время пошло!";

$bot->SendGroupMessage($msg{'reply_to'}, $txt);
}

when (/^(\w+):\s*\+[+1]+\s*$/) {
return if $1 eq $from;
$karma{lc($1)}++;
$bot->SendGroupMessage($msg{'reply_to'},
"$from: поднял карму $1 до " . $karma{lc($1)});
}

when (/^(\w+):\s*\-[-1]+\s*$/) {
return if $1 eq $from;
$karma{lc($1)}--;
$bot->SendGroupMessage($msg{'reply_to'},
"$from: опустил карму $1 до " . $karma{lc($1)});
}

when (m{(https?://\S+)}) {
my $uri = $1;
my $ua = LWP::UserAgent->new();
Expand Down Expand Up @@ -282,7 +230,7 @@ sub new_bot_message {
my $content = $response->decoded_content;

return if scalar $response->code < 200 ||
scalar $response->code >= 400;
scalar $response->code >= 300;

$content =~ m{.*<title[^>]*>(.*?)</title.*}si;

Expand Down Expand Up @@ -320,6 +268,88 @@ sub new_bot_message {
}

default {
# manual check for nick presence, performance hack
foreach my $nick (keys $jid_DB{$forum}) {
my $qnick = quotemeta($nick);

if (" $msg{body} " =~ m{$rb$qnick$rb}i) {

given ($msg{'body'}) {

when (/^(?:karma|карма)$rb*?$qnick$/i) {
$bot->SendGroupMessage($msg{'reply_to'},
"$from: карма $nick " . ($karma{lc($nick)}||0));
}

when (/^(?:bomb|бомба)$rb*?$qnick$/i) {
if ($from eq $nick) {
$bot->SendGroupMessage($msg{'reply_to'},
"$from: привык забавляться сам с собой?");
return;
}

if (defined $bomb_time{lc($nick)}) {
$bot->SendGroupMessage($msg{'reply_to'},
"$from: на $nick уже установлена бомба.");
return;
}

if (abs(time - $last_bomb_time) < 180) {
$bot->SendGroupMessage($msg{'reply_to'},
"$from: у меня ещё не восполнен боезапас. Жди.");
return;
}

$last_bomb_time = time;

my %selected_colors;
while($col_count != keys %selected_colors){
$selected_colors{$colors[int($#colors * rand)]} = 1;
}

my $selected_colors_t = join ', ', (
sort keys %selected_colors
);

$selected_colors_t =~ s/,( \S+)$/ и$1/i;

$bomb_time{lc($nick)} = time;
$bomb_correct{lc($nick)} = (keys %selected_colors)[0];
$bomb_resourse{lc($nick)} = $resource;
$bomb_nick{lc($nick)} = $nick;

my $txt = "Привет от $from, $nick! " .
"Я хочу сыграть с тобой в игру.\n" .
"Правила очень простые. " .
"Всю свою жизнь ты не уважал random, " .
"и теперь пришло время поплатиться. \n" .
"На тебе бомба, из которой торчат " .
"$selected_colors_t провода. \n" .
"Твоя задача -- правильно выбрать провод. " .
"До взрыва осталось 1-2 минуты. Время пошло!";

$bot->SendGroupMessage($msg{'reply_to'}, $txt);
}

when (/^($qnick):\s*\+[+1]+\s*$/) {
return if $nick eq $from;
$karma{lc($nick)}++;
$bot->SendGroupMessage($msg{'reply_to'},
"$from: поднял карму $nick до " . $karma{lc($nick)});
}

when (/^($qnick):\s*\-[-1]+\s*$/) {
return if $nick eq $from;
$karma{lc($nick)}--;
$bot->SendGroupMessage($msg{'reply_to'},
"$from: опустил карму $nick до " . $karma{lc($nick)});
}
}

return;
}
}

$bot->SendGroupMessage($msg{'reply_to'},
"$from: how about NO, братиша?") if $to_me;
}
Expand All @@ -343,6 +373,7 @@ sub new_bot_message {
loop_sleep_time => $loop_sleep_time,
forums_and_responses => \%forum_list,
forums_passwords => \%forum_passwords,
JidDB => \%jid_DB,
);

$bot->Start();

0 comments on commit 9691b31

Please sign in to comment.