File Coverage

blib/lib/Bot/ChatBots/Messenger/Sender.pm
Criterion Covered Total %
statement 31 32 96.8
branch 11 14 78.5
condition 2 3 66.6
subroutine 8 8 100.0
pod 1 1 100.0
total 53 58 91.3


line stmt bran cond sub pod time code
1             package Bot::ChatBots::Messenger::Sender;
2 2     2   88020 use strict;
  2         2  
  2         56  
3 2     2   8 use warnings;
  2         3  
  2         81  
4             { our $VERSION = '0.004'; }
5              
6 2     2   502 use Ouch;
  2         3728  
  2         161  
7 2     2   1142 use Log::Any qw< $log >;
  2         15459  
  2         8  
8 2     2   6179 use Mojo::URL;
  2         165461  
  2         17  
9              
10 2     2   1407 use Moo;
  2         24734  
  2         11  
11 2     2   4331 use namespace::clean;
  2         24931  
  2         15  
12              
13             with 'Bot::ChatBots::Role::Sender';
14             with 'Bot::ChatBots::Role::UserAgent';
15              
16             has token => (
17             is => 'ro',
18             required => 1,
19             );
20              
21             has url => (
22             is => 'ro',
23             default => 'https://graph.facebook.com/v2.6/me/messages',
24             );
25              
26             has _url => (
27             is => 'ro',
28             lazy => 1,
29             default => sub {
30             my $self = shift;
31             return Mojo::URL->new($self->url)
32             ->query({access_token => $self->token});
33             },
34             );
35              
36             sub send_message {
37 4     4 1 18987 my ($self, $message) = splice @_, 0, 2;
38 4 50       25 ouch 500, 'no output to send' unless defined $message;
39              
40 4 50 66     51 my %args = (@_ && ref($_[0])) ? %{$_[0]} : @_;
  0         0  
41              
42             # message normalization
43 4 100       42 $message = {message => {text => $message}} unless ref $message;
44 4 100       24 if (! exists $message->{recipient}) {
45 3 100       35 if (defined $args{record}) { # take from record
    100          
46 1         4 $message->{recipient}{id} = $args{record}{channel}{id};
47             }
48             elsif ($self->has_recipient) {
49 1         13 $message->{recipient}{id} = $self->recipient;
50             }
51             else { # no more ways to figure it out
52 1         8 ouch 500, 'no recipient for message';
53             }
54             }
55              
56             return $self->ua_request(
57             'post',
58             %args,
59             ua_args => [
60             $self->_url,
61             {Accept => 'application/json'},
62             json => $message,
63 3 50       153 ($args{callback} ? $args{callback} : ()),
64             ],
65             );
66             } ## end sub send_message
67              
68             1;