1 Commits

Author SHA1 Message Date
eleksir
4706322c4e Перерабатываем парсер команд 2022-04-22 16:22:00 +03:00
4 changed files with 93 additions and 77 deletions

View File

@@ -14,6 +14,8 @@
# Perl::Critic::Policy::ProhibitImplicitImport
# Perl::Critic::Policy::CodeLayout::RequireUseUTF8
severity = 5
verbose = 8
# minorify some of warnings that are not really critical
[-InputOutput::RequireCheckedClose]
@@ -129,5 +131,3 @@ lib_sections = NAME | VERSION | DESCRIPTION | AUTHOR | LICENSE AND COPYRIGHT
max_length = 256
[-Miscellanea::ProhibitUnrestrictedNoCritic]
[-RegularExpressions::ProhibitFixedStringMatches]

View File

@@ -47,10 +47,7 @@ my $runAsUid = $UID;
my $piddir = '/var/run/' . basename (abs_path ($PROGRAM_NAME));
my $C = LoadConf ();
my $loglevel = 'notice';
$loglevel = $C->{'loglevel'} if defined $C->{'loglevel'};
my $loglevel = $C->{'loglevel'} // 'notice';
my $logfile;
if (defined $C->{'log'}) {
@@ -139,7 +136,6 @@ close $MYPID; ## no critic (InputOutput::
# подстраховка на случай ядерной войны.
local $SIG{INT} = \&__signal_handler;
local $SIG{TERM} = \&__signal_handler;
local $SIG{QUIT} = \&__signal_handler;
# Поставим правильное имя процесса в proctitle
$PROGRAM_NAME = abs_path $PROGRAM_NAME; ## no critic (Variables::RequireLocalizedPunctuationVars)

View File

@@ -5,6 +5,7 @@ requires 'Cwd', '==3.75';
requires 'Cwd::utf8', '==0.011';
requires 'Data::Dumper', '==2.183';
requires 'Digest::SHA', '==6.02';
requires 'Encode', '==3.16';
# Part of perl
requires 'English', '0';
requires 'File::Basename', '==2.85';
@@ -17,13 +18,15 @@ 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.26';
requires 'Mojolicious', '==9.24';
# Part of Mojolicious
requires 'Mojo::IOLoop', '0';
requires 'Mojo::IOLoop::Signal', '==0.003';
requires 'Mojo::Redis', '==3.29';
requires 'Mojo::Redis', '==3.27';
# 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

@@ -19,12 +19,15 @@ use English qw ( -no_match_vars );
# Модули для работы приложения
use Clone qw (clone);
use Data::Dumper qw (Dumper);
use Digest::SHA qw (sha256_hex);
use Digest::SHA qw (sha1_base64);
use Encode qw (encode_utf8);
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);
@@ -37,16 +40,13 @@ use Exporter qw (import);
our @EXPORT_OK = qw (RunCraniac);
sub RandomCommonPhrase ();
sub utf2sha1 ($);
sub fmatch (@);
sub brains (@);
sub RunCraniac ();
my $c = LoadConf ();
my $fwd_cnt = 5;
if (defined $c->{'forward_max'}) {
$fwd_cnt = $c->{'forward_max'};
}
my $fwd_cnt = $c->{'forward_max'} // 5;
my $hailo;
@@ -69,6 +69,17 @@ 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;
@@ -86,27 +97,30 @@ sub fmatch (@) {
# Ленивая инициализация мозга. Создаём/открываем мозг только если нам надо "подумать" а не на каждую входящую фразу.
sub brains (@) {
my $plugin = shift;
my $cid = shift;
my $chatid = shift;
my $telegram = shift // 0;
unless (defined $hailo->{$cid}) {
unless (defined $hailo->{$chatid}) {
my $cid = $chatid;
my $brainname;
# Костыль, чтобы не портировать данные из телеграммных мозгов и не заниматься переименованием
if ($plugin eq 'telegram') {
$brainname = sprintf '%s/%s.brain.sqlite', $c->{braindir}, $cid;
} else {
unless ($telegram) {
$cid = utf2sha1 ($chatid);
$cid =~ s/\//-/xmsg;
$brainname = sprintf '%s/%s.sqlite', $c->{braindir}, $cid;
} else {
$brainname = sprintf '%s/%s.brain.sqlite', $c->{braindir}, $cid;
}
$hailo->{$cid} = eval {
$hailo->{$chatid} = eval {
Hailo->new (
brain => $brainname,
order => 3,
);
};
if (defined $hailo->{$cid}) {
if (defined $hailo->{$chatid}) {
$log->info (sprintf '[INFO] Lazy init brain: %s', $brainname);
} else {
$log->error ("[ERROR] $EVAL_ERROR");
@@ -344,20 +358,19 @@ 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-х букв.
if (length ($m->{message}) > 3) {
my $telegram = 0;
# Костыль для совместимости со старым наименованием "мозгов".
if ($m->{plugin} eq 'telegram') {
$telegram = 1;
}
# Lazy brain init
if (brains ($m->{plugin}, $cid)) {
$reply = $hailo->{$cid}->learn_reply ($m->{message});
if (brains ($chatid, $telegram)) {
$reply = $hailo->{$chatid}->learn_reply ($m->{message});
# Если из реактора вернулся undef выдаём "общую" фразу из словаря.
unless (defined $reply) {
@@ -384,9 +397,14 @@ my $parse_message = sub {
} else {
# Пытаемся что-то запоминать, если фраза длиннее 3-х букв
if (length ($m->{message}) > 3) {
# Lazy brain init
if (brains ($m->{plugin}, $cid)) {
$hailo->{$cid}->learn ($m->{message});
my $telegram = 0;
if ($m->{plugin} eq 'telegram') {
$telegram = 1;
}
if (brains ($chatid, $telegram)) {
$hailo->{$chatid}->learn ($m->{message});
}
}
}
@@ -450,7 +468,6 @@ sub RunCraniac () {
Mojo::IOLoop::Signal->on (TERM => $__signal_handler);
Mojo::IOLoop::Signal->on (INT => $__signal_handler);
Mojo::IOLoop::Signal->on (QUIT => $__signal_handler);
do { Mojo::IOLoop->start } until Mojo::IOLoop->is_running;
return;