15 Commits
v1.1 ... v1.4

Author SHA1 Message Date
eleksir
dcb3204c9e Update modules versions, get rid of Protocol::Redis::XS as it is broken on recent versions of libhiredis 2022-05-31 03:52:19 +03:00
eleksir
e6d8e4c1a2 Use sha256_hex of plugin name and chatid as filename for brains in commin case 2022-05-31 03:49:22 +03:00
eleksir
ca982571d9 Reimplement commands parser 2022-04-22 16:28:02 +03:00
eleksir
03634958a1 Fix typo 2022-04-22 15:46:19 +03:00
eleksir
6eeb8e7b89 Tidy incomming redis message 2022-04-22 15:42:23 +03:00
eleksir
7b32737b33 Use cloned version of incomming redis message as template for outgoing message 2022-04-22 15:01:20 +03:00
eleksir
8952828886 Use command sign from config, when misc->bot_nick is not supplied, it defaults to empty string 2022-04-22 15:00:04 +03:00
eleksir
221314ae16 Userid and chatid must be strings in order to work with chats components other than Telegram 2022-04-22 14:58:26 +03:00
eleksir
27b9a4bcbd Set each async signal handler separately 2022-04-22 14:57:14 +03:00
eleksir
98bf57c5e0 In cpanfile bump Mojolicious version 9.22->9.24, zero English version - it's part of perl 2022-04-22 14:56:01 +03:00
eleksir
7565539a14 Update .gitignore 2022-04-22 14:53:38 +03:00
eleksir
0a62499302 Update README 2022-04-17 15:28:58 +03:00
eleksir
f256ad357f Add list of perlcritic modules used for linting 2022-04-03 18:19:35 +03:00
eleksir
62311dae21 Fix typo in кости command, use shorter var name for csign 2022-04-03 18:18:38 +03:00
eleksir
30ebe8aca1 Set userid and chatid explicitly to num for redis json msg 2022-03-27 16:06:43 +03:00
6 changed files with 179 additions and 163 deletions

2
.gitignore vendored
View File

@@ -5,5 +5,7 @@ _Deparsed_XSubs.pm
*.pid
*.log
data/cache/**
data/brains/**
data/lat/**
data/config.json
vendor_perl/**

View File

@@ -1,4 +1,19 @@
#!/usr/bin/env perlcritic
# Задействованные модули критика:
#
# Perl::Critic::More
# Perl::Critic::Pulp
# Perl::Critic::TooMuchCode
# Perl::Critic::Lax
# Perl::Critic::CognitiveComplexity
# Perl::Critic::Policy::CompileTime
# Perl::Critic::Policy::ProhibitImplicitImport
# Perl::Critic::Policy::Dynamic::NoIndirect
# Perl::Critic::StricterSubs
# Perl::Critic::Policy::ProhibitImplicitImport
# Perl::Critic::Policy::CodeLayout::RequireUseUTF8
severity = 5
verbose = 8

10
README
View File

@@ -6,18 +6,18 @@ aleesa-craniac
Механика работы
-----------------------------------------------------------------------------------------------------------------------
Бредогенератор подписан на redis-канал craniac. В этот канал пишет другой демоночек - aleesa-misc. Причём, особенность
такова, что если aleesa-misc не распознала фразу, как команду для другого модуля, то по-умолчанию такая фраза
оправляется в канал craniac, то есть сюда, в "мозги".
Бредогенератор подписан на redis-канал craniac. В этот канал пишет другой демоночек - aleesa-misc-go. Причём,
особенность такова, что если aleesa-misc не распознала фразу, как команду для другого модуля, то по-умолчанию такая
фраза оправляется в канал craniac, то есть сюда, в "мозги".
У бредогенератора есть 2 типа входящих сообщений - ключевые фразы, на которые у него есть готовые (статические) ответы
и остальные, для которых ему надо решить нужен ли ответ и по-необходимости сгенерировать его, используя данные в цепях
Маркова.
Ответ направляется в redis-канал, указанный в поле plugin входящего сообщения, если не предполагается некоей особой
логики, связанной с easter egg поведением.
логики, связанной, наприме, с easter egg поведением.
Формат протокола - см. README от aleesa-misc.
Формат протокола - см. README от aleesa-misc-go.
Как это запустить?

View File

@@ -1,11 +1,12 @@
## no critic
requires 'Carp', '==1.50';
requires 'Clone', '==0.45';
requires 'Cwd', '==3.75';
requires 'Cwd::utf8', '==0.011';
requires 'Data::Dumper', '==2.183';
requires 'Digest::SHA', '==6.02';
requires 'Encode', '==3.16';
requires 'English', '==1.11';
# Part of perl
requires 'English', '0';
requires 'File::Basename', '==2.85';
requires 'File::Path', '==2.18';
requires 'File::Spec', '==3.75';
@@ -16,15 +17,13 @@ requires 'Log::Any', '==1.710';
requires 'Log::Any::Adapter', '==1.710';
requires 'Log::Any::For::Std', '==0.05';
requires 'Math::Random::Secure', '==0.080001';
requires 'Mojolicious', '==9.22';
requires 'Mojolicious', '==9.26';
# Part of Mojolicious
requires 'Mojo::IOLoop', '0';
requires 'Mojo::IOLoop::Signal', '==0.003';
requires 'Mojo::Redis', '==3.27';
requires 'Mojo::Redis', '==3.29';
# Part of perl
requires 'POSIX', '0';
# Buggy, latest version works, as pub-sub, but fails tests
requires 'Protocol::Redis::XS', '0';
requires 'Text::Fuzzy', '==0.29';
# Part of perl
requires 'utf8', '0';

View File

@@ -25,7 +25,10 @@
# maximal amount of message forwardings, to avoid endless loops
"forwards_max" : 5,
"lat" : {
# Command prefix aka command sign
"csign" : "!",
"lat" : {
"brain" : "data/lat/brain.sqlite",
"src" : "data/lat.txt"
}

View File

@@ -17,16 +17,14 @@ use open qw (:std :utf8);
use English qw ( -no_match_vars );
# Модули для работы приложения
use Clone qw (clone);
use Data::Dumper qw (Dumper);
use Digest::SHA qw (sha1_base64);
use Encode qw (encode_utf8);
use Digest::SHA qw (sha256_hex);
use File::Spec ();
use Hailo ();
use Log::Any qw ($log);
use Mojo::IOLoop ();
use Mojo::IOLoop::Signal ();
# Чтобы "уж точно" использовать hiredis-биндинги, загрузим этот модуль перед Mojo::Redis
use Protocol::Redis::XS ();
use Mojo::Redis ();
use Math::Random::Secure qw (irand);
use Text::Fuzzy qw (distance_edits);
@@ -39,7 +37,6 @@ use Exporter qw (import);
our @EXPORT_OK = qw (RunCraniac);
sub RandomCommonPhrase ();
sub utf2sha1 ($);
sub fmatch (@);
sub brains (@);
sub RunCraniac ();
@@ -68,17 +65,6 @@ sub RandomCommonPhrase () {
return $myphrase[irand ($#myphrase + 1)];
}
sub utf2sha1 ($) {
my $string = shift;
if ($string eq '') {
return sha1_base64 '';
}
my $bytes = encode_utf8 $string;
return sha1_base64 $bytes;
}
sub fmatch (@) {
my $srcphrase = shift;
my $answer = shift;
@@ -96,30 +82,27 @@ sub fmatch (@) {
# Ленивая инициализация мозга. Создаём/открываем мозг только если нам надо "подумать" а не на каждую входящую фразу.
sub brains (@) {
my $chatid = shift;
my $telegram = shift // 0;
my $plugin = shift;
my $cid = shift;
unless (defined $hailo->{$chatid}) {
my $cid = $chatid;
unless (defined $hailo->{$cid}) {
my $brainname;
# Костыль, чтобы не портировать данные из телеграммных мозгов и не заниматься переименованием
unless ($telegram) {
$cid = utf2sha1 ($chatid);
$cid =~ s/\//-/xmsg;
$brainname = sprintf '%s/%s.sqlite', $c->{braindir}, $cid;
} else {
if ($plugin eq 'telegram') {
$brainname = sprintf '%s/%s.brain.sqlite', $c->{braindir}, $cid;
} else {
$brainname = sprintf '%s/%s.sqlite', $c->{braindir}, $cid;
}
$hailo->{$chatid} = eval {
$hailo->{$cid} = eval {
Hailo->new (
brain => $brainname,
order => 3,
);
};
if (defined $hailo->{$chatid}) {
if (defined $hailo->{$cid}) {
$log->info (sprintf '[INFO] Lazy init brain: %s', $brainname);
} else {
$log->error ("[ERROR] $EVAL_ERROR");
@@ -133,115 +116,150 @@ sub brains (@) {
# Основной парсер
my $parse_message = sub {
my $self = shift;
my $m = shift;
my $m = shift;
my $answer = clone ($m);
$answer->{from} = 'craniac';
my $send_to = $m->{plugin};
my $chatid = $m->{chatid};
my $userid = $m->{userid};
my $phrase = $m->{message};
my $reply;
# Если $m->{misc}->{answer} не существует, то проставим его как 1, предполагаем, что по-умолчанию ответ от нас
# всё-таки ожидают. Если что - уточним ниже.
if (defined $m->{misc}) {
unless (defined $m->{misc}->{fwd_cnt}) {
$m->{misc}->{fwd_cnt} = 1;
} else {
if ($m->{misc}->{fwd_cnt} > $fwd_cnt) {
$log->error ('[ERROR] Forward loop detected, discarding message.');
$log->debug (Dumper $m);
return;
} else {
$m->{misc}->{fwd_cnt}++;
if (defined $answer->{misc}) {
unless (defined $answer->{misc}->{answer}) {
$answer->{misc}->{answer} = 1;
}
}
unless (defined $m->{misc}->{answer}) {
$m->{misc}->{answer} = 1;
}
unless (defined $answer->{misc}->{bot_nick}) {
$answer->{misc}->{bot_nick} = '';
}
unless (defined $m->{misc}->{csign}) {
$m->{misc}->{csign} = '!';
}
unless (defined $answer->{misc}->{csign}) {
$answer->{misc}->{csign} = $c->{csign};
}
# TODO: не проставлять дефолтный ник!
unless (defined $m->{misc}->{bot_nick}) {
$m->{misc}->{bot_nick} = 'aleesa';
}
unless (defined $answer->{misc}->{fwd_cnt}) {
$answer->{misc}->{fwd_cnt} = 1;
} else {
if ($answer->{misc}->{fwd_cnt} > $fwd_cnt) {
$log->error ('[ERROR] Forward loop detected, discarding message.');
$log->debug (Dumper $m);
return;
} else {
$answer->{misc}->{fwd_cnt}++;
}
}
unless (defined $answer->{misc}->{good_morning}) {
$answer->{misc}->{good_morning} = 0;
}
unless (defined $answer->{misc}->{msg_format}) {
$answer->{misc}->{msg_format} = 0;
}
unless (defined $answer->{misc}->{username}) {
$answer->{misc}->{username} = 'user';
}
} else {
$m->{misc}->{answer} = 1;
$m->{misc}->{csign} = '!';
$m->{misc}->{bot_nick} = 'aleesa';
$answer->{misc}->{answer} = 1;
$answer->{misc}->{bot_nick} = '';
$answer->{misc}->{csign} = $c->{csign};
$answer->{misc}->{fwd_cnt} = 1;
$answer->{misc}->{good_morning} = 0;
$answer->{misc}->{msg_format} = 0;
$answer->{misc}->{username} = 'user';
}
if (defined $m->{misc}->{bot_nick}) {
my $csign = $answer->{misc}->{csign};
$answer->{message} = '';
my $is_command = 0;
my $cmd = $m->{message};
if ($m->{message} =~ /^\Q$csign/u) {
$cmd = substr $m->{message}, length ($csign);
$is_command = 1;
}
if ($m->{misc}->{bot_nick} ne '') {
# Если нам сообщили ник бота, попробуем вымарать его из оригинального текста сообщения, в большинстве случаев он
# нам не интересн.
# нам не интересен.
$phrase =~ s/\s*\,?\s*($m->{misc}->{bot_nick})\s*\,?\s*/ /gui;
# TODO: проработать реакцию на "пьяный бред".
# В ключевых фразах можно обратиться с некоторыми командами к боту по нику, не используя символ команды
if ($m->{message} =~ /^\s*\Q;m->{misc}->{bot_nick}\E\s*;/ui) {
if ($m->{message} =~ /^\s*\Q$m->{misc}->{bot_nick}\E\s*$/ui) {
$reply = 'Чего?';
} elsif ($m->{message} =~ /^(\Q$m->{misc}->{csign}\E|\Q$m->{misc}->{bot_nick}\E\s*\,?\s+)ping\.?\s*$/i) {
} elsif ($m->{message} =~ /^(\Q$csign\E|\Q$m->{misc}->{bot_nick}\E\s*\,?\s+)ping\.?\s*$/i) {
$reply = 'Pong.';
} elsif ($m->{message} =~ /^(\Q$m->{misc}->{csign}\E|\Q$m->{misc}->{bot_nick}\E\s*\,?\s+)pong\.?\s*$/i) {
} elsif ($m->{message} =~ /^(\Q$csign\E|\Q$m->{misc}->{bot_nick}\E\s*\,?\s+)pong\.?\s*$/i) {
$reply = 'Wat?';
} elsif ($m->{message} =~ /^(\Q$m->{misc}->{csign}\E|\Q$m->{misc}->{bot_nick}\E\s*\,?\s+)пин(г|х)\.?\s*$/ui) {
} elsif ($m->{message} =~ /^(\Q$csign\E|\Q$m->{misc}->{bot_nick}\E\s*\,?\s+)пин(г|х)\.?\s*$/ui) {
$reply = 'Понг.';
} elsif ($m->{message} =~ /^(\Q$m->{misc}->{csign}\E|\Q$m->{misc}->{bot_nick}\E\s*\,?\s+)пон(г|х)\.?\s*$/ui) {
} elsif ($m->{message} =~ /^(\Q$csign\E|\Q$m->{misc}->{bot_nick}\E\s*\,?\s+)пон(г|х)\.?\s*$/ui) {
$reply = 'Шта?';
} elsif ($m->{message} =~ /^(\Q$m->{misc}->{csign}\E|\Q$m->{misc}->{bot_nick}\E\s*\,?\s+)(хэлп|halp)\s*$/ui) {
} elsif ($m->{message} =~ /^(\Q$csign\E|\Q$m->{misc}->{bot_nick}\E\s*\,?\s+)(хэлп|halp)\s*$/ui) {
$reply = 'HALP!!!11';
}
} else {
# Если нам не сообщили ник бота, то ищем команды, используя символ команды
if ($m->{message} =~ /^\Q$m->{misc}->{csign}\Eping\.?\s*$/ui) {
$reply = 'Pong.';
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\Epong\.?\s*$/i) {
$reply = 'Wat?';
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\Eпин(г|х)\.?\s*$/ui) {
$reply = 'Понг.';
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\Eпон(г|х)\.?\s*$/ui) {
$reply = 'Шта?';
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\E(хэлп|halp)\s*$/ui) {
$reply = 'HALP!!!11';
if ($is_command) {
if ($cmd =~ /^ping\.?\s*$/ui) {
$reply = 'Pong.';
} elsif ($cmd =~ /^pong\.?\s*$/i) {
$reply = 'Wat?';
} elsif ($cmd=~ /^пин(г|х)\.?\s*$/ui) {
$reply = 'Понг.';
} elsif ($cmd =~ /^пон(г|х)\.?\s*$/ui) {
$reply = 'Шта?';
} elsif ($cmd=~ /^(хэлп|halp)\s*$/ui) {
$reply = 'HALP!!!11';
}
}
}
# Поищем в тексте входящего сообщения команды общего плана, с символом команды.
unless (defined $reply) {
if ($m->{message} =~ /^\Q$m->{misc}->{csign}\E(kde|кде)\s*$/ui) {
my @phrases = (
'Нет, я не буду поднимать вам плазму.',
'Повторяйте эту мантру по утрам не менее 5 раз: "Плазма не падает." И, возможно, она перестанет у вас падать.',
'Плазма не падает, она просто выходит отдохнуть.',
'Плазма это не агрегатное состояние, это суперпозиция. Во время работы она находится сразу в жидком, мягком и тёплом состояниях.',
);
if ($is_command) {
if ($cmd =~ /^(kde|кде)\s*$/ui) {
my @phrases = (
'Нет, я не буду поднимать вам плазму.',
'Повторяйте эту мантру по утрам не менее 5 раз: "Плазма не падает." И, возможно, она перестанет у вас падать.',
'Плазма не падает, она просто выходит отдохнуть.',
'Плазма это не агрегатное состояние, это суперпозиция. Во время работы она находится сразу в жидком, мягком и тёплом состояниях.',
);
$reply = $phrases[irand ($#phrases + 1)];
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\E(coin|монетка)$/ui) {
if (rand (101) < 0.016) {
$reply = 'ребро';
} else {
if (irand (2) == 0) {
if (irand (2) == 0) {
$reply = 'орёл';
} else {
$reply = 'аверс';
}
$reply = $phrases[irand ($#phrases + 1)];
} elsif ($cmd =~ /^(coin|монетка)$/ui) {
# Нам тут говорили, что есть некая вероятность, что монета упадёт ребром... И даже цифры называли.
if (rand (101) < 0.016) {
$reply = 'ребро';
} else {
if (irand (2) == 0) {
$reply = 'решка';
if (irand (2) == 0) {
$reply = 'орёл';
} else {
$reply = 'аверс';
}
} else {
$reply = 'реверс';
if (irand (2) == 0) {
$reply = 'решка';
} else {
$reply = 'реверс';
}
}
}
} elsif ($cmd =~ /^(roll|dice|кости)$/ui) {
$reply = sprintf 'На первой кости выпало %d, а на второй — %d.', irand (6) + 1, irand (6) + 1;
} elsif ($cmd =~ /^(ver|version|версия)$/ui) {
$reply = 'Версия: Четыре.Технологическое_превью';
} elsif ($cmd =~ /^(lat|лат)\s*$/ui) {
$reply = Lat ();
}
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\E(roll|dice|кости')$/ui) {
$reply = sprintf 'На первой кости выпало %d, а на второй — %d.', irand (6) + 1, irand (6) + 1;
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\E(ver|version|версия)$/ui) {
$reply = 'Версия: Четыре.Технологическое_превью';
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\E(lat|лат)\s*$/ui) {
$reply = Lat ();
}
}
@@ -249,14 +267,10 @@ my $parse_message = sub {
# общения - публичного или приватного.
if (defined $reply) {
if ($m->{misc}->{answer}) {
$answer->{message} = $reply;
$self->json ($send_to)->notify (
$send_to => {
from => 'craniac',
userid => $userid,
chatid => $chatid,
plugin => $m->{plugin},
message => $reply,
},
$send_to => $answer,
);
}
} else {
@@ -294,14 +308,10 @@ my $parse_message = sub {
# TODO: дописать запрос в webapp, для easter egg-ов, либо делать это на уровне aleesa-misc
if (defined ($reply) && $m->{misc}->{answer}) {
$answer->{message} = $reply;
$self->json ($send_to)->notify (
$send_to => {
from => 'craniac',
userid => $userid,
chatid => $chatid,
plugin => $m->{plugin},
message => $reply,
},
$send_to => $answer,
);
return;
@@ -319,14 +329,10 @@ my $parse_message = sub {
}
if (defined ($reply) && $m->{misc}->{answer}) {
$answer->{message} = $reply;
$self->json ($send_to)->notify (
$send_to => {
from => 'craniac',
userid => $userid,
chatid => $chatid,
plugin => $m->{plugin},
message => $reply,
},
$send_to => $answer,
);
return;
@@ -334,56 +340,49 @@ my $parse_message = sub {
}
# Попадаем сюда только если входящая фраза не распознана ранее как ключевая.
my $cid;
if ($m->{plugin} eq 'telegram') {
$cid = $chatid;
} else {
$cid = sha256_hex (sprintf '%s/%s', $m->{plugin}, $chatid);
}
if ($m->{misc}->{answer}) {
# Пытаемся что-то генерировать, если фраза длиннее 3-х букв
# Пытаемся что-то генерировать, если фраза длиннее 3-х букв.
if (length ($m->{message}) > 3) {
my $telegram = 0;
if ($m->{plugin} eq 'telegram') {
$telegram = 1;
}
# Lazy brain init
if (brains ($chatid, $telegram)) {
$reply = $hailo->{$chatid}->learn_reply ($m->{message});
if (brains ($m->{plugin}, $cid)) {
$reply = $hailo->{$cid}->learn_reply ($m->{message});
# Если из реактора вернулся undef выдаём "общую" фразу из словаря
# Если из реактора вернулся undef выдаём "общую" фразу из словаря.
unless (defined $reply) {
$reply = RandomCommonPhrase ();
} else {
# Если из реактора вернулась пустота выдаём "общую" фразу из словаря
# Если из реактора вернулась пустота выдаём "общую" фразу из словаря.
if ($reply eq '') {
$reply = RandomCommonPhrase ();
}
# Если сгенерированная фраза слишком похожа на начальную - выдаём "общую" фразу из словаря
# Если сгенерированная фраза слишком похожа на начальную - выдаём "общую" фразу из словаря.
if (fmatch (lc ($m->{message}), lc ($reply))) {
$reply = RandomCommonPhrase ();
}
}
$answer->{message} = $reply;
$self->json ($send_to)->notify (
$send_to => {
from => 'craniac',
userid => $userid,
chatid => $chatid,
plugin => $m->{plugin},
message => $reply,
},
$send_to => $answer,
);
}
}
} else {
# пытаемся что-то запоминать, если фраза длиннее 3-х букв
# Пытаемся что-то запоминать, если фраза длиннее 3-х букв
if (length ($m->{message}) > 3) {
my $telegram = 0;
if ($m->{plugin} eq 'telegram') {
$telegram = 1;
}
if (brains ($chatid, $telegram)) {
$hailo->{$chatid}->learn ($m->{message});
# Lazy brain init
if (brains ($m->{plugin}, $cid)) {
$hailo->{$cid}->learn ($m->{message});
}
}
}
@@ -445,10 +444,8 @@ sub RunCraniac () {
);
}
Mojo::IOLoop::Signal->on (
TERM => $__signal_handler,
INT => $__signal_handler,
);
Mojo::IOLoop::Signal->on (TERM => $__signal_handler);
Mojo::IOLoop::Signal->on (INT => $__signal_handler);
do { Mojo::IOLoop->start } until Mojo::IOLoop->is_running;
return;