5 Commits
v1.0 ... v1.2

Author SHA1 Message Date
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
8 changed files with 145 additions and 110 deletions

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
@@ -94,3 +109,25 @@ 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]

9
README
View File

@@ -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,8 @@ my $runAsUid = $UID;
my $piddir = '/var/run/' . basename (abs_path ($PROGRAM_NAME));
my $C = LoadConf ();
my $loglevel = $C->{'loglevel'} // 'info';
my $loglevel = $C->{'loglevel'} // 'notice';
my $logfile;
my $log;
if (defined $C->{'log'}) {
$logfile = $C->{'log'};
@@ -69,8 +71,8 @@ if ($UID == 0) {
make_path (
$piddir, {
uid => $uid,
group => $gid
}
group => $gid,
},
);
}
@@ -81,8 +83,8 @@ if ($UID == 0) {
make_path (
$logdir, {
uid => $uid,
group => $gid
}
group => $gid,
},
) or die "Unable to create $logdir: $OS_ERROR\n";
}
}
@@ -95,9 +97,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 +115,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");
@@ -141,7 +143,7 @@ $PROGRAM_NAME = abs_path $PROGRAM_NAME; ## no critic (Variables::Re
# И запустим уже наш сервис
RunCraniac ();
if (-f $pidfile) {
if (-e $pidfile) {
unlink $pidfile;
}
@@ -149,8 +151,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 +176,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,31 @@
## no critic
requires 'Carp', '==1.50';
requires 'Cwd', '0';
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';
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';
# Part of Mojolicious
requires 'Mojo::IOLoop', '0';
requires 'Mojo::IOLoop::Signal', '==0.003';
requires 'Mojo::Log', '0';
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';
requires 'version', '==0.9929';

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,17 @@ use open qw (:std :utf8);
use English qw ( -no_match_vars );
# Модули для работы приложения
use Data::Dumper qw (Dumper);
use Digest::SHA qw (sha1_base64);
use Hailo;
use Mojo::IOLoop;
use Mojo::IOLoop::Signal;
use Mojo::Log;
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 Protocol::Redis::XS ();
use Mojo::Redis ();
use Math::Random::Secure qw (irand);
use Text::Fuzzy qw (distance_edits);
@@ -42,22 +45,7 @@ sub brains (@);
sub RunCraniac ();
my $c = LoadConf ();
my $loglevel = $c->{'loglevel'} // 'info';
my $fwd_cnt = $c->{'forward_max'} // 5;
my $logfile;
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');
}
my $hailo;
@@ -127,7 +115,7 @@ sub brains (@) {
$hailo->{$chatid} = eval {
Hailo->new (
brain => $brainname,
order => 3
order => 3,
);
};
@@ -185,43 +173,45 @@ my $parse_message = sub {
$m->{misc}->{bot_nick} = 'aleesa';
}
my $csign = $m->{misc}->{csign};
if (defined $m->{misc}->{bot_nick}) {
# Если нам сообщили ник бота, попробуем вымарать его из оригинального текста сообщения, в большинстве случаев он
# нам не интересн.
$phrase =~ s/\s*\,?\s*($m->{misc}->{bot_nick})\s*\,?\s*/ /gui;
# В ключевых фразах можно обратиться с некоторыми командами к боту по нику, не используя символ команды
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) {
if ($m->{message} =~ /^\Q$csign\Eping\.?\s*$/ui) {
$reply = 'Pong.';
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\Epong\.?\s*$/i) {
} elsif ($m->{message} =~ /^\Q$csign\Epong\.?\s*$/i) {
$reply = 'Wat?';
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\Eпин(г|х)\.?\s*$/ui) {
} elsif ($m->{message} =~ /^\Q$csign\Eпин(г|х)\.?\s*$/ui) {
$reply = 'Понг.';
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\Eпон(г|х)\.?\s*$/ui) {
} elsif ($m->{message} =~ /^\Q$csign\Eпон(г|х)\.?\s*$/ui) {
$reply = 'Шта?';
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\E(хэлп|halp)\s*$/ui) {
} elsif ($m->{message} =~ /^\Q$csign\E(хэлп|halp)\s*$/ui) {
$reply = 'HALP!!!11';
}
}
# Поищем в тексте входящего сообщения команды общего плана, с символом команды.
unless (defined $reply) {
if ($m->{message} =~ /^\Q$m->{misc}->{csign}\E(kde|кде)\s*$/ui) {
if ($m->{message} =~ /^\Q$csign\E(kde|кде)\s*$/ui) {
my @phrases = (
'Нет, я не буду поднимать вам плазму.',
'Повторяйте эту мантру по утрам не менее 5 раз: "Плазма не падает." И, возможно, она перестанет у вас падать.',
@@ -230,7 +220,7 @@ my $parse_message = sub {
);
$reply = $phrases[irand ($#phrases + 1)];
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\E(coin|монетка)$/ui) {
} elsif ($m->{message} =~ /^\Q$csign\E(coin|монетка)$/ui) {
if (rand (101) < 0.016) {
$reply = 'ребро';
} else {
@@ -248,11 +238,11 @@ my $parse_message = sub {
}
}
}
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\E(roll|dice|кости')$/ui) {
} elsif ($m->{message} =~ /^\Q$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) {
} elsif ($m->{message} =~ /^\Q$csign\E(ver|version|версия)$/ui) {
$reply = 'Версия: Четыре.Технологическое_превью';
} elsif ($m->{message} =~ /^\Q$m->{misc}->{csign}\E(lat|лат)\s*$/ui) {
} elsif ($m->{message} =~ /^\Q$csign\E(lat|лат)\s*$/ui) {
$reply = Lat ();
}
}
@@ -264,11 +254,11 @@ my $parse_message = sub {
$self->json ($send_to)->notify (
$send_to => {
from => 'craniac',
userid => $userid,
chatid => $chatid,
userid => 0 + $userid,
chatid => 0 + $chatid,
plugin => $m->{plugin},
message => $reply
}
message => $reply,
},
);
}
} else {
@@ -309,11 +299,11 @@ my $parse_message = sub {
$self->json ($send_to)->notify (
$send_to => {
from => 'craniac',
userid => $userid,
chatid => $chatid,
userid => 0 + $userid,
chatid => 0 + $chatid,
plugin => $m->{plugin},
message => $reply
}
message => $reply,
},
);
return;
@@ -334,11 +324,11 @@ my $parse_message = sub {
$self->json ($send_to)->notify (
$send_to => {
from => 'craniac',
userid => $userid,
chatid => $chatid,
userid => 0 + $userid,
chatid => 0 + $chatid,
plugin => $m->{plugin},
message => $reply
}
message => $reply,
},
);
return;
@@ -377,11 +367,11 @@ my $parse_message = sub {
$self->json ($send_to)->notify (
$send_to => {
from => 'craniac',
userid => $userid,
chatid => $chatid,
userid => 0 + $userid,
chatid => 0 + $chatid,
plugin => $m->{plugin},
message => $reply
}
message => $reply,
},
);
}
}
@@ -408,7 +398,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 +411,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 +428,11 @@ sub RunCraniac () {
my ($conn, $error) = @_;
$log->error ("[ERROR] Redis connection error: $error");
return;
}
},
);
return;
}
},
);
my $pubsub = $redis->pubsub;
@@ -453,13 +443,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
INT => $__signal_handler,
);
do { Mojo::IOLoop->start } until Mojo::IOLoop->is_running;

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 ();