21 Commits
v1.0 ... v1.5

Author SHA1 Message Date
eleksir
b3a8a1724c Add SIGQUIT handler, fix setting of default value of loglevel 2022-11-06 18:12:35 +03:00
eleksir
e100b00838 Fix setting default value for forward_max if not defined in config 2022-11-06 18:01:30 +03:00
eleksir
499da4fe84 Fix whitespaces in Craniac.pm :) 2022-09-02 00:07:19 +03:00
eleksir
f4d738697c Add exception to perlcritic policies, remove verbosity settings from .perlcriticrc 2022-09-02 00:06:33 +03:00
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
eleksir
bbc5173c16 Update README 2022-02-12 19:13:21 +03:00
eleksir
622b690946 Perlcritic overhaul, add missing 'use module', update cpanfile, replace Mojo::Log with Log::Any
* Use more strict policy in perlcritic (add more policies)
* Add missing Use Encode and Use File::Spec in Craniac.pm
* Replace Mojo::Log with Log::Any, as Log::Any can catch stacktraces
* Update cpanfile
2022-02-12 19:08:00 +03:00
10 changed files with 273 additions and 230 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,6 +1,19 @@
#!/usr/bin/env perlcritic
severity = 5
verbose = 8
# Задействованные модули критика:
#
# 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
# minorify some of warnings that are not really critical
[-InputOutput::RequireCheckedClose]
@@ -94,3 +107,27 @@ lib_sections = NAME | VERSION | DESCRIPTION | AUTHOR | LICENSE AND COPYRIGHT
# Have to use it, so fuckoff
[-Variables::ProhibitPackageVars]
[-CodeLayout::RequireASCII]
[-Editor::RequireEmacsFileVariables]
[-TooMuchCode::ProhibitUnnecessaryUTF8Pragma]
[-TooMuchCode::ProhibitDuplicateLiteral]
[-ErrorHandling::RequireUseOfExceptions]
[-ValuesAndExpressions::RequireConstantOnLeftSideOfEquality]
[-Lax::RequireConstantOnLeftSideOfEquality::ExceptEq]
[-Lax::ProhibitEmptyQuotes::ExceptAsFallback]
[-CodeLayout::RequireUseUTF8]
[ValuesAndExpressions::RestrictLongStrings]
max_length = 256
[-Miscellanea::ProhibitUnrestrictedNoCritic]
[-RegularExpressions::ProhibitFixedStringMatches]

19
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.
Как это запустить?
@@ -32,8 +32,11 @@ aleesa-craniac
Если всё хорошо, то после запуска redis-а, создания data/config.json из data/config_sample.json, можно запускать и само
приложение.
В каталоге contrib находится скрипт для alpine linux, системы инициализации openrc. Этот скрипт достаточно положить В
/etc/init.d/aleesa-craniac сконфигурить сервис по инструкции выше и после этого сервис запускается командой:
В каталоге contrib находится скрипт для alpine linux, системы инициализации openrc.
Этот скрипт достаточно положить в /etc/init.d/aleesa-craniac, сконфигурить сервис по инструкции выше и, после этого,
сервис запускается командой:
service aleesa-craniac start
в автозагрузку его можно прописать через команду
В автозагрузку его можно прописать через команду:
rc-update add aleesa-craniac default

View File

@@ -1,6 +1,6 @@
#!/usr/bin/perl
use 5.018;
use 5.018; ## no critic (ProhibitImplicitImport)
use strict;
use warnings;
use utf8;
@@ -29,7 +29,10 @@ no Cwd;
use Cwd::utf8 qw (chdir abs_path);
use File::Basename qw (basename dirname);
use File::Path qw (make_path);
use Mojo::Log;
use File::Spec ();
use Log::Any qw ($log);
use Log::Any::Adapter ();
use Log::Any::For::Std ();
use POSIX qw (setgid setuid setsid);
use Conf qw (LoadConf);
@@ -44,9 +47,11 @@ my $runAsUid = $UID;
my $piddir = '/var/run/' . basename (abs_path ($PROGRAM_NAME));
my $C = LoadConf ();
my $loglevel = $C->{'loglevel'} // 'info';
my $loglevel = 'notice';
$loglevel = $C->{'loglevel'} if defined $C->{'loglevel'};
my $logfile;
my $log;
if (defined $C->{'log'}) {
$logfile = $C->{'log'};
@@ -69,8 +74,8 @@ if ($UID == 0) {
make_path (
$piddir, {
uid => $uid,
group => $gid
}
group => $gid,
},
);
}
@@ -81,8 +86,8 @@ if ($UID == 0) {
make_path (
$logdir, {
uid => $uid,
group => $gid
}
group => $gid,
},
) or die "Unable to create $logdir: $OS_ERROR\n";
}
}
@@ -95,9 +100,9 @@ if ($UID == 0) {
}
if (defined $logfile) {
$log = Mojo::Log->new (path => $logfile, level => $loglevel);
Log::Any::Adapter->set ('File', $logfile, log_level => $loglevel);
} else {
$log = Mojo::Log->new (path => '/dev/null', level => 'fatal');
Log::Any::Adapter->set ('File', File::Spec->devnull);
}
# По-умолчанию, демонизируемся, если явно не указано, что этого делать не надо
@@ -113,7 +118,7 @@ my $apath = abs_path $PROGRAM_NAME;
unless (defined $apath) {
$log->fatal ("[FATAL] Unable to get abs_path: $OS_ERROR\n");
exit 1;
};
}
my $pidfile = sprintf '%s/%s.pid', $piddir, basename $apath;
$log->info ("[INFO] Creating pidfile at $pidfile");
@@ -134,6 +139,7 @@ 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)
@@ -141,7 +147,7 @@ $PROGRAM_NAME = abs_path $PROGRAM_NAME; ## no critic (Variables::Re
# И запустим уже наш сервис
RunCraniac ();
if (-f $pidfile) {
if (-e $pidfile) {
unlink $pidfile;
}
@@ -149,8 +155,8 @@ exit 0;
sub daemonize {
__fork ();
POSIX::setsid ();
open STDIN, '<', '/dev/null'; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
setsid ();
open STDIN, '<', File::Spec->devnull; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
__fork ();
umask 0;
return;
@@ -174,7 +180,7 @@ sub __fork {
sub __signal_handler {
$log->info ("[INFO] Caught a signal $OS_ERROR");
if (-f $pidfile) {
if (-e $pidfile) {
unlink $pidfile;
}

View File

@@ -1,7 +1,7 @@
#!/usr/bin/perl
# Наполняет отдельный "мозг" с бредом латинскими выражениями
use 5.018;
use 5.018; ## no critic (ProhibitImplicitImport)
use strict;
use warnings;
use utf8;

View File

@@ -1,22 +1,30 @@
## no critic
requires 'Carp', '==1.50';
requires 'Cwd', '0';
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';
requires 'File::Basename', '0';
# Part of perl
requires 'English', '0';
requires 'File::Basename', '==2.85';
requires 'File::Path', '==2.18';
requires 'File::Spec', '==3.75';
requires 'Hailo', '==0.75';
requires 'JSON::XS', '==4.03';
requires 'local::lib', '==2.000028';
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::Log', '0';
requires 'Mojo::Redis', '==3.27';
requires 'Mojo::Redis', '==3.29';
# Part of perl
requires 'POSIX', '0';
requires 'Protocol::Redis::XS', '0';
requires 'Text::Fuzzy', '==0.29';
# Part of perl
requires 'utf8', '0';
requires 'version', '==0.9929';

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

@@ -1,14 +1,13 @@
package Conf;
# loads config
# Загружает конфиг файл
use 5.018;
use 5.018; ## no critic (ProhibitImplicitImport)
use strict;
use warnings;
use utf8;
use open qw (:std :utf8);
use English qw ( -no_match_vars );
use Encode qw (encode decode);
use JSON::XS;
use JSON::XS ();
use version; our $VERSION = qw (1.0);
use Exporter qw (import);
@@ -16,17 +15,26 @@ our @EXPORT_OK = qw (LoadConf);
sub LoadConf {
my $c = 'data/config.json';
open my $CH, '<', $c or die "[FATAL] No conf at $c: $OS_ERROR\n";
my $json;
my $CH;
unless (open $CH, '<', $c) {
die "[FATAL] No conf at $c: $OS_ERROR\n";
}
my $len = (stat $c) [7];
my $json;
my $readlen = read $CH, $json, $len;
$json = encode 'UTF-8', $json;
unless ($readlen) {
close $CH; ## no critic (InputOutput::RequireCheckedSyscalls
die "[FATAL] Unable to read $c: $OS_ERROR\n";
}
if ($readlen != $len) {
close $CH; ## no critic (InputOutput::RequireCheckedSyscalls
die "[FATAL] File $c is $len bytes on disk, but we read only $readlen bytes\n";
}
close $CH; ## no critic (InputOutput::RequireCheckedSyscalls
my $j = JSON::XS->new->utf8->relaxed;
return $j->decode ($json);

View File

@@ -9,7 +9,7 @@ package Craniac;
# проигнорировать.
# Общие модули - синтаксис, кодировки итд
use 5.018;
use 5.018; ## no critic (ProhibitImplicitImport)
use strict;
use warnings;
use utf8;
@@ -17,14 +17,15 @@ use open qw (:std :utf8);
use English qw ( -no_match_vars );
# Модули для работы приложения
use Digest::SHA qw (sha1_base64);
use Hailo;
use Mojo::IOLoop;
use Mojo::IOLoop::Signal;
use Mojo::Log;
# Чтобы "уж точно" использовать hiredis-биндинги, загрузим этот модуль перед Mojo::Redis
use Protocol::Redis::XS;
use Mojo::Redis;
use Clone qw (clone);
use Data::Dumper qw (Dumper);
use Digest::SHA qw (sha256_hex);
use File::Spec ();
use Hailo ();
use Log::Any qw ($log);
use Mojo::IOLoop ();
use Mojo::IOLoop::Signal ();
use Mojo::Redis ();
use Math::Random::Secure qw (irand);
use Text::Fuzzy qw (distance_edits);
@@ -36,27 +37,15 @@ use Exporter qw (import);
our @EXPORT_OK = qw (RunCraniac);
sub RandomCommonPhrase ();
sub utf2sha1 ($);
sub fmatch (@);
sub brains (@);
sub RunCraniac ();
my $c = LoadConf ();
my $loglevel = $c->{'loglevel'} // 'info';
my $fwd_cnt = $c->{'forward_max'} // 5;
my $logfile;
my $log;
my $fwd_cnt = 5;
if (defined $c->{'log'}) {
$logfile = $c->{'log'};
} elsif (defined $c->{'debug_log'}) {
$logfile = $c->{'debug_log'};
}
if (defined $logfile) {
$log = Mojo::Log->new (path => $logfile, level => $loglevel);
} else {
$log = Mojo::Log->new (path => '/dev/null', level => 'fatal');
if (defined $c->{'forward_max'}) {
$fwd_cnt = $c->{'forward_max'};
}
my $hailo;
@@ -80,17 +69,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;
@@ -108,30 +86,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
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");
@@ -145,115 +120,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;
if (defined $answer->{misc}) {
unless (defined $answer->{misc}->{answer}) {
$answer->{misc}->{answer} = 1;
}
unless (defined $answer->{misc}->{bot_nick}) {
$answer->{misc}->{bot_nick} = '';
}
unless (defined $answer->{misc}->{csign}) {
$answer->{misc}->{csign} = $c->{csign};
}
unless (defined $answer->{misc}->{fwd_cnt}) {
$answer->{misc}->{fwd_cnt} = 1;
} else {
if ($m->{misc}->{fwd_cnt} > $fwd_cnt) {
if ($answer->{misc}->{fwd_cnt} > $fwd_cnt) {
$log->error ('[ERROR] Forward loop detected, discarding message.');
$log->debug (Dumper $m);
return;
} else {
$m->{misc}->{fwd_cnt}++;
$answer->{misc}->{fwd_cnt}++;
}
}
unless (defined $m->{misc}->{answer}) {
$m->{misc}->{answer} = 1;
unless (defined $answer->{misc}->{good_morning}) {
$answer->{misc}->{good_morning} = 0;
}
unless (defined $m->{misc}->{csign}) {
$m->{misc}->{csign} = '!';
unless (defined $answer->{misc}->{msg_format}) {
$answer->{misc}->{msg_format} = 0;
}
# TODO: не проставлять дефолтный ник!
unless (defined $m->{misc}->{bot_nick}) {
$m->{misc}->{bot_nick} = 'aleesa';
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 ();
}
}
@@ -261,14 +271,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 {
@@ -306,14 +312,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;
@@ -331,14 +333,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;
@@ -346,56 +344,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});
}
}
}
@@ -408,7 +399,7 @@ my $__signal_handler = sub {
my ($self, $name) = @_;
$log->info ("[INFO] Caught a signal $name");
if (defined $main::pidfile && -f $main::pidfile) {
if (defined $main::pidfile && -e $main::pidfile) {
unlink $main::pidfile;
}
@@ -421,7 +412,7 @@ sub RunCraniac () {
$log->info ("[INFO] Connecting to $c->{server}, $c->{port}");
my $redis = Mojo::Redis->new (
sprintf 'redis://%s:%s/1', $c->{server}, $c->{port}
sprintf 'redis://%s:%s/1', $c->{server}, $c->{port},
);
$log->info ('[INFO] Registering connection-event callback');
@@ -438,11 +429,11 @@ sub RunCraniac () {
my ($conn, $error) = @_;
$log->error ("[ERROR] Redis connection error: $error");
return;
}
},
);
return;
}
},
);
my $pubsub = $redis->pubsub;
@@ -453,14 +444,13 @@ sub RunCraniac () {
$log->debug ("[DEBUG] Subscribing to $channel");
$sub->{$channel} = $pubsub->json ($channel)->listen (
$channel => sub { $parse_message->(@_); }
$channel => sub { $parse_message->(@_); },
);
}
Mojo::IOLoop::Signal->on (
TERM => $__signal_handler,
INT => $__signal_handler
);
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;

View File

@@ -1,7 +1,7 @@
package Craniac::Lat;
# Крылатые латинские выражения спёрты с https://ru.wikipedia.org/wiki/Список_крылатых_латинских_выражений
use 5.018;
use 5.018; ## no critic (ProhibitImplicitImport)
use strict;
use warnings;
use utf8;
@@ -10,8 +10,8 @@ use English qw ( -no_match_vars );
use Carp qw (cluck);
use File::Basename qw (dirname);
use File::Path qw (make_path);
use Hailo;
use Mojo::Log;
use Hailo ();
use Log::Any qw ($log);
use Conf qw (LoadConf);
@@ -25,20 +25,6 @@ my $brain_order = 2;
my $c = LoadConf ();
my $brain = $c->{lat}->{brain};
my $srcfile = $c->{lat}->{src};
my $loglevel = $c->{'loglevel'} // 'info';
my $log;
if (defined $c->{'log'}) {
$logfile = $c->{'log'};
} elsif (defined $c->{'debug_log'}) {
$logfile = $c->{'debug_log'};
}
if (defined $logfile) {
$log = Mojo::Log->new (path => $logfile, level => $loglevel);
} else {
$log = Mojo::Log->new (path => '/dev/null', level => 'fatal');
}
sub Train () {
my $braindir = dirname $brain;
@@ -52,7 +38,7 @@ sub Train () {
my $lat = Hailo->new (
brain => $brain,
order => $brain_order
order => $brain_order,
);
$lat->train ($srcfile);
@@ -71,7 +57,7 @@ sub Lat () {
return '';
}
unless (-f $brain) {
unless (-e $brain) {
$log->error ("[ERROR] No lat module data: $brain is absent! Train lat first.");
return '';
}
@@ -79,7 +65,7 @@ sub Lat () {
my $lat = Hailo->new (
brain => $brain,
order => $brain_order,
save_on_exit => 0
save_on_exit => 0,
);
return $lat->reply ();