| 1 | package Bot::BasicBot::CommandBot; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use 5.014; | ||
| 6 | |||
| 7 | use Tie::RegexpHash 0.16; | ||
| 8 | use List::Util qw(any); | ||
| 9 | |||
| 10 | use Exporter 'import'; | ||
| 11 | use base qw/Bot::BasicBot/; | ||
| 12 | |||
| 13 | our @EXPORT_OK = qw(command); | ||
| 14 | |||
| 15 | my %command; | ||
| 16 | |||
| 17 | sub command { | ||
| 18 | (caller)[0]->declare_command(@_); | ||
| 19 | } | ||
| 20 | |||
| 21 | sub declare_command { | ||
| 22 | my $package = shift; | ||
| 23 | my $sub = pop; | ||
| 24 | my $command = pop; | ||
| 25 | |||
| 26 | my %options = @_; | ||
| 27 | |||
| 28 | $options{events} //= ['said']; | ||
| 29 | |||
| 30 | if (not exists $command{$package}) { | ||
| 31 | $command{$package} = {}; | ||
| 32 | tie %{$command{$package}}, 'Tie::RegexpHash'; | ||
| 33 | } | ||
| 34 | |||
| 35 | $command{$package}{$command} = { | ||
| 36 | sub => $sub, | ||
| 37 | %options, | ||
| 38 | }; | ||
| 39 | } | ||
| 40 | |||
| 41 | |||
| 42 | sub new { | ||
| 43 | my $class = shift; | ||
| 44 | my %opts = @_; | ||
| 45 | |||
| 46 | my $address = delete $opts{address}; | ||
| 47 | my $trigger = delete $opts{trigger}; | ||
| 48 | |||
| 49 | my $self = $class->SUPER::new(%opts); | ||
| 50 | $self->{trigger} = $trigger if defined $trigger; | ||
| 51 | $self->{address} = $address if defined $address; | ||
| 52 | |||
| 53 | return $self; | ||
| 54 | } | ||
| 55 | |||
| 56 | sub said { | ||
| 57 | my $self = shift; | ||
| 58 | my ($data) = @_; | ||
| 59 | |||
| 60 | my $package = ref $self; | ||
| 61 | |||
| 62 | if (my @auto = $self->_auto($data->{body}) { | ||
| 63 | return join " ", @auto; | ||
| 64 | } | ||
| 65 | |||
| 66 | if ($self->{address} and not $data->{address}) { | ||
| 67 | return; | ||
| 68 | } | ||
| 69 | |||
| 70 | if ($self->{trigger} and $data->{body} !~ s/^\Q$self->{trigger}//) { | ||
| 71 | return; | ||
| 72 | } | ||
| 73 | |||
| 74 | my ($cmd, $message) = split ' ', $data->{body}, 2; | ||
| 75 | my $found = $command{$package}{$cmd} or return "What is $cmd?"; | ||
| 76 | |||
| 77 | any { $_ eq 'said' } @{$found->{events}} or return; | ||
| 78 | |||
| 79 | $found->{sub}->($self, $cmd, $message); | ||
| 80 | } | ||
| 81 | |||
| 82 | sub emoted { | ||
| 83 | } | ||
| 84 | |||
| 85 | sub noticed { | ||
| 86 | } | ||
| 87 | |||
| 88 | sub _auto { } | ||
| 89 | |||
| 90 | 1; | ||
| 91 | |||
| 92 | __END__ |