blib/lib/AnyEvent/SlackBot.pm

filter: Statementstmt 29.1% 61 / 209 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 6 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 40.0% 16 / 40 Podpod 80.0% 8 / 10 totaltotal 25.8% 85 / 329 CC 33 SCAR 30.5
CC
33
Cov
22%
__ANON__
56.0
__ANON__
56.0
connect_and_run
42.0
CRAP 21.1
↑ Summary
1 package AnyEvent::SlackBot;
2  
3 1 ▶use Modern::Perl;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use MooX::Types::MooseLike::Base qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use HTTP::Request::Common qw(POST);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use AnyEvent::HTTP::MultiGet;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use AnyEvent::WebSocket::Client;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use IO::Socket::SSL;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 our $VERSION='1.0005';
18  
19 1 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶ no namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 with 'Log::LogMethods','Data::Result::Moo';
22 }
23
24  
25 =head1 NAME
26  
27 AnyEvent::SlackBot - AnyEvent Driven Slack Bot Interface
28  
29 =head1 SYNOPSIS
30  
31 use Modern::Perl;
32 use Data::Dumper;
33 use AnyEvent::SlackBot;
34 use AnyEvent::Loop;
35  
36 $|=1;
37 my $sb=AnyEvent::SlackBot->new(
38 on_event=>sub {
39 my ($sb,$json,$conn_data)=@_;
40 if(exists $json->{type} and $json->{type} eq 'desktop_notification') {
41 my $ref={
42 type=>'message',
43 bot_id=>$sb->bot_id,
44 channel=>$json->{channel},
45 text=>'this is a test',
46 subtype=>'bot_message',
47 };
48 print Dumper($json,$ref);
49 $sb->send($ref);
50 }
51 },
52 );
53  
54 my $result=$sb->connect_and_run;
55 die $result unless $result;
56 AnyEvent::Loop::run;
57  
58 =head1 DESCRIPTION
59  
60 Slack client. Handles Ping Pong on idle conntions, and transparrently reconnects as needed. The guts of the module wrap AnyEvent::WebSocket::Client, keeping the code base very light.
61  
62 =head1 OO Arguments and accessors
63  
64 Required Arguments
65  
66 on_event: code refrence for handling events
67 sub { my ($self,$connection,$message,$startup_info)=@_ }
68  
69 Optional Arguments
70  
71 on_idle: code refrence for use in idle time
72 sub { my ($self)=@_ }
73  
74 on_reply: code refrence called when the server responds to a post
75 sub { my ($self,$json,$connection_data)=@_ }
76  
77 agent: Sets the AnyEvent::HTTP::MultiGet Object
78 logger: sets the logging object, DOES( Log::Log4perl::Logger )
79 rtm_start_url: the url used to fetch the websockets connection from
80 token: the authentication token used by rtm_start_url
81 auto_reconnect: if true ( default ) reconnects when a connection fails
82 unknown_que: array ref of objects that may be repeats from us
83  
84 Set at Run time
85  
86 connection: The connection object
87 bot_id: The Bot ID defined at runtime
88 stats: An anonyous hash ref of useful stats
89  
90 =cut
91  
92 has unknown_que=>(
93 is=>'ro',
94 isa=>ArrayRef,
95 0 ▶ default=>sub { [] },
Subroutine __ANON__: not called CC=1 SCAR=6.9
96 1 required=>1,
97 );
98  
99 has on_reply=>(
100 is=>'ro',
101 isa=>CodeRef,
102 0 ▶ default=>sub { sub {} },
Subroutine __ANON__: not called CC=1 SCAR=6.9
Subroutine __ANON__: not called CC=1 SCAR=6.9
103 1 required=>1,
104 );
105  
106 has agent=>(
107 is=>'ro',
108 isa=>Object,
109 0 ▶ default=>sub { new AnyEvent::HTTP::MultiGet() },
Subroutine __ANON__: not called CC=1 SCAR=6.9
110 1 );
111  
112 1 has rtm_start_url=>(
113 is=>'ro',
114 isa=>Str,
115 required=>1,
116 default=>'https://slack.com/api/rtm.start',
117 );
118  
119 has on_idle=>(
120 is=>'ro',
121 isa=>CodeRef,
122 required=>1,
123 0 ▶ default=>sub { sub {} }
Subroutine __ANON__: not called CC=1 SCAR=6.9
Subroutine __ANON__: not called CC=1 SCAR=6.9
124 1 );
125  
126 1 has token=>(
127 is=>'ro',
128 isa=>Str,
129 required=>1,
130 );
131  
132 has stats=>(
133 is=>'ro',
134 isa=>HashRef,
135 required=>1,
136 0 ▶ default=>sub { {} },
Subroutine __ANON__: not called CC=1 SCAR=6.9
137 1 );
138  
139 1 has on_event=>(
140 is=>'ro',
141 isa=>CodeRef,
142 requried=>1,
143 );
144  
145 1 has auto_reconnect=>(
146 is=>'rw',
147 isa=>Bool,
148 required=>1,
149 default=>1,
150 );
151  
152 1 has connection=>(
153 is=>'rw',
154 isa=>Object,
155 required=>0,
156 );
157  
158 1 has bot_id=>(
159 is=>'rw',
160 isa=>Str,
161 required=>0,
162 );
163  
164 1 has keep_alive_timeout =>(
165 is=>'ro',
166 isa=>Int,
167 requried=>1,
168 default=>15,
169 );
170  
171 # This method runs after the new constructor
172 0 ▶sub BUILD {
Subroutine BUILD: not called CC=1 SCAR=6.9
Pod undocumented
173 0 my ($self)=@_;
174  
175 0 $self->{backlog}=[];
176 0 $self->{ignore}={};
177 0 $self->stats->{service_started_on}=time;
178 0 $self->stats->{running_posts}=0;
179 }
180  
181 # this method runs before the new constructor, and can be used to change the arguments passed to the module
182 0 ▶around BUILDARGS => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
183 0 my ($org,$class,@args)=@_;
184
185 0 return $class->$org(@args);
186 1 };
187  
188 =head1 OO Methods
189  
190 =over 4
191  
192 =item * $self->connect_and_run
193  
194 COnnects and starts running
195  
196 =cut
197  
198 0 ▶sub connect_and_run {
Subroutine connect_and_run: not called CC=6 SCAR=37.4
Pod documented
199 0 my ($self)=@_;
200 0 my $request=POST $self->rtm_start_url,[token=>$self->token];
201 0 my $ua=LWP::UserAgent->new;
202 0 $ua->ssl_opts(
203 SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE,
204 SSL_hostname => '',
205 verify_hostname => 0
206 );
207 0 my $response=$ua->request($request);
208 0 $self->{timer}=undef;
209 0 ▶ if($response->code==200) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->code == 200) { } 0 0 0
210 0 my $data=eval { from_json($response->decoded_content) };
211 0 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
212 0 return $self->new_false("Failed to decode response, error was: $@");
213 }
214 0 ▶ unless(exists $data->{url} and $data->{self}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $data->{"url"} and $data->{"self"}) 0 0 0
Condition0%0/3
exists $data->{"url"} and $data->{"self"}
!ll&&!rl&&r
000
MC/DC0%0/2
exists $data->{"url"} and $data->{"self"}
exists $data->{"url"} $data->{"self"}
Truth table0%0/3
A and B
A= exists $data->{"url"}B= $data->{"self"}
ABresult
0X0
100
111
215 0 ▶ my $msg=exists $data->{error} ? $data->{error} : 'unknown slack error';
Branch: 1 branch
BranchTrueFalseTotal
exists $data->{'error'} ? : 0 0 0
216 0 return $self->new_false("Failed to get valid connection info, error was: $msg");
217 }
218  
219 0 $self->build_connection($data);
220 } else {
221 0 return $self->new_false("Failed to get conenction info from slack, error was: ".$response->status_line);
222 }
223 }
224  
225 =item * my $id=$self->next_id
226  
227 Provides an id for the next message.
228  
229 =cut
230  
231 0 ▶sub next_id {
Subroutine next_id: not called CC=1 SCAR=6.9
Pod documented
232 0 my ($self)=@_;
233 return ++$self->{next_id}
234 0 }
235  
236 =item * if($self->is_connected) { ... }
237  
238 Denotes if we are currently connected to slack
239  
240 =cut
241  
242 0 ▶sub is_connected {
Subroutine is_connected: not called CC=1 SCAR=6.9
Pod undocumented
243 0 return defined($_[0]->connection)
244 }
245  
246 =item * $self->send($ref)
247  
248 Converts $ref to json and sends it on the session.
249  
250 =cut
251  
252 0 ▶sub send {
Subroutine send: not called CC=2 SCAR=17.9
Pod documented
253 0 my ($self,$ref)=@_;
254 0 my $json=to_json($ref);
255 0 ▶ if($self->connection) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->connection) { } 0 0 0
256 0 $self->connection->send($json);
257 0 ++$self->stats->{total_messages_sent};
258 } else {
259 0 push @{$self->{backlog}},$json;
260 }
261 }
262  
263 =item * $self->send_typing($json)
264  
265 Given $json sends a currently typing reply
266  
267 =cut
268  
269 0 ▶sub send_typing {
Subroutine send_typing: not called CC=1 SCAR=6.9
Pod documented
270 0 my ($self,$json)=@_;
271 0 my $id=$self->next_id;
272 my $msg={
273 bot_id=>$self->bot_id,
274 channel=>$json->{channel},
275 0 id=>$id,
276 type=>'typing',
277 };
278 0 $self->send($msg);
279 }
280  
281 =item * $self->post_to_web($msg,$endpoint|undef,"FORM"|"JSON"|undef)
282  
283 Posts the to the given REST Endpoint outside of the WebSocket.
284  
285 msg:
286 Hash ref representing the requrest being sent
287 token: set to $self->token if not set
288 scope: set to: 'chat:write:bot' if not set
289  
290 endpoint:
291 The Rest xxx endpint, the default is 'chat.postMessage'
292  
293 type:
294 Sets how the data will be sent over
295 Supported options are:
296 - FORM: posts the data using form encoding
297 - JSON: converts $msg to a json string and posts
298  
299 =cut
300  
301 0 ▶sub post_to_web {
Subroutine post_to_web: not called CC=5 SCAR=34.0
Pod documented
302 0 my ($self,$msg,$endpoint,$type)=@_;
303 0 ▶ $endpoint='chat.postMessage' unless defined($endpoint);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $endpoint 0 0 0
304 0 $type='FORM';
305  
306 0 $self->stats->{running_posts}++;
307 0 my $url="https://slack.com/api/$endpoint";
308  
309  
310 0 ▶ $msg->{token}=$self->token unless exists $msg->{token};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $msg->{"token"} 0 0 0
311 0 ▶ $msg->{scope}='chat:write:bot' unless exists $msg->{scope};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $msg->{"scope"} 0 0 0
312  
313 0 my $request;
314  
315 0 ▶ if($type eq 'FORM') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq 'FORM') { } 0 0 0
316 0 $request=POST $url,[%{$msg}];
317 } else {
318 0 $request=POST $url,'Conent-Type'=>'application/json',Content=>to_json($msg);
319 }
320  
321 0 ▶ $self->agent->add_cb($request,sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
322 0 my ($agent,$request,$response)=@_;
323 0 ++$self->stats->{http_posts_sent};
324 0 $self->stats->{running_posts}--;
325 0 ▶ if($response->code!=200) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->code != 200) { } 0 0 0
326 0 $self->log_error("Failed to send Message,error was: ".$response->status_line) ;
327 } else {
328 0 my $json=eval { from_json($response->decoded_content) };
329 0 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
330 0 $self->log_error("Failed to parse json response, error was: $@")
331 } else {
332 0 $self->{ignore}->{$json->{ts}}++;
333 0 ▶ $self->log_error("Slack Responded with an eror: $json->{error}".Dumper($json)) unless $json->{ok};
Branch: 1 branch
BranchTrueFalseTotal
unless $json->{"ok"} 0 0 0
334 }
335 }
336  
337 0 ▶ if($self->stats->{running_posts}==0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->stats->{"running_posts"} == 0) 0 0 0
338 # some times we get a response from the websocet before
339 # the http request completes
340  
341 0 ▶ BACKLOG: while(my $args=shift @{$self->unknown_que}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $args = shift @{$self->unknown_que;}) 0 0 0
342 0 my (undef,$ref,$data)=@{$args};
343 0 $self->log_info("processing backlog event");
344  
345 0 ▶ next if $self->we_sent_msg($ref);
Branch: 1 branch
BranchTrueFalseTotal
if $self->we_sent_msg($ref) 0 0 0
346  
347 0 $self->on_event->($self,$ref,$data);
348 }
349 }
350 0 });
351 0 $self->agent->run_next;
352 }
353  
354 =item * if($self->we_sent_msg($json,$connection_data)) { ... }
355  
356 When true, $json is a duplicate from something we sent
357  
358 =cut
359  
360 0 ▶sub we_sent_msg {
Subroutine we_sent_msg: not called CC=4 SCAR=30.0
Pod documented
361 0 my ($self,$ref,$data)=@_;
362 0 ▶ if(exists $ref->{msg}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $ref->{'msg'}) { } 0 0 0
elsif (exists $ref->{'reply_to'}) { } 0 0 0
363 0 my $sent=delete $self->{ignore}->{$ref->{msg}};
364 0 ▶ if(defined($sent)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sent) 0 0 0
365 0 $self->info("This is a message we sent");
366 0 $self->on_reply->($self,$ref,$data);
367 0 return 1;;
368 }
369 } elsif(exists $ref->{reply_to}) {
370 0 $self->info("This is a message we sent");
371 0 $self->on_reply->($self,$ref,$data);
372 0 return 1;
373 } else {
374 0 $self->debug(Dumper($ref));
375 }
376 0 return 0;
377 }
378  
379 =item * $self->build_connection($connection_details)
380  
381 Internal Method used for buiding connections.
382  
383 =cut
384  
385 0 ▶sub build_connection {
Subroutine build_connection: not called CC=1 SCAR=6.9
Pod documented
386 0 my ($self,$data)=@_;
387 0 my $url=$data->{url};
388 0 $self->bot_id($data->{self}->{id});
389  
390 0 my $client=AnyEvent::WebSocket::Client->new;
391 0 ▶ $client->connect($url)->cb(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
392 0 my $connection=eval { shift->recv };
393 0 $self->connection($connection);
394  
395 0 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
396 0 $self->log_error("Failed to cnnect to our web socket, error was: $@");
397 0 return $self->handle_reconnect;
398 }
399 0 $self->stats->{last_connected_on}=time;
400 0 $self->stats->{total_connections}++;
401 0 $self->stats->{last_msg_on}=time;
402 $self->{timer}=AnyEvent->timer(
403 interval=>$self->keep_alive_timeout,
404 after=>$self->keep_alive_timeout,
405 0 ▶ cb=>sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
406 0 my $max_timeout=$self->stats->{last_msg_on} + 3 * $self->keep_alive_timeout;
407 0 ▶ if(time < $max_timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (time < $max_timeout) { } 0 0 0
408 0 ▶ if(time > $self->stats->{last_msg_on} + $self->keep_alive_timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (time > $self->stats->{"last_msg_on"} + $self->keep_alive_timeout) 0 0 0
409 0 $self->log_info("sending keep alive to server");
410 0 $connection->send(to_json({
411 id=>$self->next_id,
412 type=>'ping',
413 timestamp=>time,
414 }));
415 0 %{$self->{ignore}}=();
416 0 $self->on_idle->($self);
417 0 $self->stats->{last_idle_on}=time;
418 }
419 } else {
420 0 return $self->handle_reconnect;
421 }
422 }
423 0 );
424  
425 0 ▶ $self->connection->on(finish=>sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
426 0 return $self->handle_reconnect;
427 0 });
428 0 ▶ $self->connection->on(each_message=> sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
429 0 my ($connection,$message)=@_;
430 0 $self->stats->{last_msg_on}=time;
431 0 $self->stats->{total_messages_recived}++;
432 0 ▶ if($message->is_text) {
Branch: 1 branch
BranchTrueFalseTotal
if ($message->is_text) 0 0 0
433 0 my $ref=eval { from_json($message->body) };
434 0 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
435 0 $self->log_error("Failed to parse json body, error was: $@");
436 0 return $self->handle_reconnect;
437 }
438 0 ▶ if(exists $ref->{type} and $ref->{type} eq 'pong') {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $ref->{'type'} and $ref->{'type'} eq 'pong') { } 0 0 0
Condition0%0/3
exists $ref->{"type"} and $ref->{"type"} eq "pong"
!ll&&!rl&&r
000
MC/DC0%0/2
exists $ref->{"type"} and $ref->{"type"} eq "pong"
exists $ref->{"type"} $ref->{"type"} eq "pong"
Truth table0%0/3
A and B
A= exists $ref->{"type"}B= $ref->{"type"} eq "pong"
ABresult
0X0
100
111
439 0 $self->log_info("got keep alive response from server");
440 } else {
441 0 ▶ if($self->stats->{running_posts}!=0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->stats->{'running_posts'} != 0) { } 0 0 0
442 # Don't try to handle unknown commands while we are waiting on a post to go out!
443 0 push @{$self->unknown_que},[$self,$ref,$data];
444 0 $self->log_info("HTTP Post response pending.. will hold off on responding to commands until we know if we sent it or not");
445 0 return;
446 } else {
447 0 ▶ return if $self->we_sent_msg($ref,$data);
Branch: 1 branch
BranchTrueFalseTotal
if $self->we_sent_msg($ref, $data) 0 0 0
448 0 $self->log_info("real time response");
449 0 $self->debug('Inbound message: ',Dumper($ref));
450 0 $self->on_event->($self,$ref,$data);
451 }
452 }
453 }
454 0 });
455  
456 0 });
457  
458 }
459  
460 =item * $self->handle_reconnect
461  
462 Internal method used to reconnect.
463  
464 =cut
465  
466 0 ▶sub handle_reconnect {
Subroutine handle_reconnect: not called CC=5 SCAR=34.0
Pod documented
467 0 my ($self)=@_;
468 0 ▶ $self->connection->close if $self->connection;
Branch: 1 branch
BranchTrueFalseTotal
if $self->connection 0 0 0
469 0 $self->{connection}=undef;
470 0 ▶ if($self->auto_reconnect) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->auto_reconnect) 0 0 0
471 0 my $result=$self->connect_and_run;
472 0 ▶ if($result) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result) { } 0 0 0
473 0 $self->log_info("auto reconnected without an error, flushing backlog of outbound messages");
474 0 ▶ while(my $msg=shift @{$self->{backlog}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $msg = shift @{$$self{"backlog"};}) 0 0 0
475 0 $self->send($msg);
476 }
477 } else {
478 0 $self->log_error("Failed to reconnect will try again in 15 seconds, error was: $result");
479 $self->{timer}=AnyEvent->timer(
480 interval=>$self->keep_alive_timeout,
481 after=>$self->keep_alive_timeout,
482 0 ▶ cb=>sub { $self->handle_reconnect },
Subroutine __ANON__: not called CC=1 SCAR=6.9
483 0 );
484 }
485 }
486 }
487  
488 =back
489  
490 =head1 See Also
491  
492 The slack api documentation - L<https://api.slack.com/rtm>
493  
494 The AnyEvent WebSocket Client library - L<AnyEvent::WebSocket::Client>
495  
496 The AnyEvent HTTP Client library - L<AnyEvent::HTTP::MultiGet>
497  
498 =head1 AUTHOR
499  
500 Michael Shipper L<mailto:AKALINUX@CPAN.ORG>
501  
502 =cut
503  
504 1 1;
↑ Summary