CommandBot.pm untested

filter: Statementstmt 0.0% 0 / 73 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 13 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 135 CC 9 SCAR 26.1
CC
9
Cov
0%
said
42.0
new
12.0
declare_command
6.0
CRAP 13.6
1 package Bot::BasicBot::CommandBot;
2  
3 use strict;
4 use warnings;
5 use 5.014;
6  
7 our $VERSION = 0.05;
8  
9 use Tie::RegexpHash 0.16;
10 use List::Util qw(any);
11  
12 use Exporter 'import';
13 use base qw/Bot::BasicBot/;
14  
15 our @EXPORT_OK = qw(command autocommand);
16  
17 my %command;
18 my %autocommand;
19  
20 sub command {
21 (caller)[0]->declare_command(@_);
22 }
23  
24 sub autocommand {
25 (caller)[0]->declare_autocommand(@_);
26 }
27  
28 sub declare_autocommand {
29 my ($package, $sub) = @_;
30 $autocommand{$package} = $sub;
31 }
32  
33 sub declare_command {
34 my $package = shift;
35 my $sub = pop;
36 my $command = pop;
37  
38 my %options = @_;
39  
40 $options{events} //= ['said'];
41  
42 if (not exists $command{$package}) {
43 $command{$package} = {};
44 tie %{$command{$package}}, 'Tie::RegexpHash';
45 }
46  
47 $command{$package}{$command} = {
48 sub => $sub,
49 %options,
50 };
51 }
52  
53  
54 sub new {
55 my $class = shift;
56 my %opts = @_;
57  
58 my $address = delete $opts{address};
59 my $trigger = delete $opts{trigger};
60 my $bark = delete $opts{bark} // 1;
61  
62 my $self = $class->SUPER::new(%opts);
63 $self->{trigger} = $trigger if defined $trigger;
64 $self->{address} = $address if defined $address;
65 $self->{bark} = $bark;
66  
67 return $self;
68 }
69  
70 sub said {
71 my $self = shift;
72 my ($data) = @_;
73  
74 $self->{command} = $data;
75 my $package = ref $self;
76  
77 my ($cmd, $message) = split ' ', $data->{body}, 2;
78  
79 my $autosay = $self->_auto($data->{body});
80  
81 if ($self->{address} and not $data->{address}) {
82 return $autosay;
83 }
84  
85 if ($self->{trigger} and $data->{body} !~ s/^\Q$self->{trigger}//) {
86 return $autosay;
87 }
88  
89 my $found = $command{$package}{$cmd};
90  
91 if (!$found) {
92 return "What is $cmd?" if $self->{bark};
93 return $autosay;
94 }
95  
96 my $say;
97 if (any { $_ eq 'said' } @{$found->{events}}) {
98 $say = $found->{sub}->($self, $cmd, $message);
99 }
100  
101 return $say // $autosay;
102 }
103  
104 sub emoted {
105 }
106  
107 sub noticed {
108 }
109  
110 sub _auto {
111 my ($self, $message) = @_;
112 join ' ', map $_->($self, $message), values %autocommand;
113 }
114  
115 1;
116  
117 __END__