blib/lib/Bot/Backbone/Service/SlackChat.pm untested

filter: Statementstmt 0.0% 0 / 166 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 3 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 29 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 279 SCAR 69.0
CC
31
Cov
0%
load_channel
56.0
load_user
42.0
mark_read
30.0
CRAP 992.0
1 package Bot::Backbone::Service::SlackChat;
2 $Bot::Backbone::Service::SlackChat::VERSION = '0.161740';
3 use v5.14;
4 use Bot::Backbone::Service;
5  
6 with qw(
7 Bot::Backbone::Service::Role::Service
8 Bot::Backbone::Service::Role::Dispatch
9 Bot::Backbone::Service::Role::BareMetalChat
10 Bot::Backbone::Service::Role::GroupJoiner
11 );
12  
13 use Bot::Backbone::Message;
14 use Carp;
15 use CHI;
16 use Encode;
17 use AnyEvent::SlackRTM;
18 use WebService::Slack::WebApi;
19  
20 # ABSTRACT: Connect and chat with a Slack server
21  
22  
23 has token => (
24 is => 'ro',
25 isa => 'Str',
26 required => 1,
27 );
28  
29  
30 # To avoid Slack rate limiting
31 has cache => (
32 is => 'ro',
33 required => 1,
34 lazy => 1,
35 builder => '_build_cache',
36 );
37  
38 sub _build_cache {
39 CHI->new(
40 driver => 'Memory',
41 datastore => {},
42 expires_in => 60, # let's not bother to cache for long
43 );
44 }
45  
46 # This is kind of kludgey. It needs work. Not documenting it in the POD for now
47 # because it is very likely to change.
48 has last_mark => (
49 is => 'rw',
50 isa => 'Int',
51 required => 1,
52 default => 0,
53 );
54  
55  
56 has api => (
57 is => 'ro',
58 isa => 'WebService::Slack::WebApi',
59 lazy => 1,
60 builder => '_build_api',
61 );
62  
63 sub _build_api {
64 my $self = shift;
65 WebService::Slack::WebApi->new(token => $self->token);
66 }
67  
68  
69 has rtm => (
70 is => 'ro',
71 isa => 'AnyEvent::SlackRTM',
72 lazy => 1,
73 builder => '_build_rtm',
74 );
75  
76 sub _build_rtm {
77 my $self = shift;
78 AnyEvent::SlackRTM->new($self->token);
79 }
80  
81  
82 has error_callback => (
83 is => 'ro',
84 isa => 'CodeRef',
85 lazy => 1,
86 builder => '_build_error_callback',
87 );
88  
89 sub _build_error_callback {
90 return sub {
91 my ($self, $rtm, $message) = @_;
92 carp "Slack Error #$message->{error}{code}: $message->{error}{msg}\n";
93 }
94 }
95  
96  
97 has whoami => (
98 is => 'rw',
99 isa => 'HashRef',
100 required => 1,
101 lazy => 1,
102 builder => '_build_whoami',
103 );
104  
105 sub _build_whoami {
106 my $self = shift;
107 my $res = $self->api->auth->test;
108  
109 if ($res->{ok}) {
110 $res;
111 }
112 else {
113 croak "unable to ask Slack who am I?";
114 }
115 }
116  
117  
118 sub user { shift->whoami->{user} }
119 sub user_id { shift->whoami->{user_id} }
120 sub team_id { shift->whoami->{team_id} }
121  
122  
123 sub initialize {
124 my $self = shift;
125  
126 $self->rtm->on(
127 message => sub { $self->got_message(@_) },
128 error => sub { $self->error_callback->($self, @_) }
129 );
130  
131 $self->rtm->quiet(1);
132  
133 $self->rtm->start;
134 }
135  
136  
137 sub _cached {
138 my ($self, $key, $code) = @_;
139  
140 my $cached = $self->cache->get($key);
141 return $cached if $cached;
142  
143 my $value = $code->();
144 $self->cache->set($key, $value);
145 return $value;
146 }
147  
148 sub load_user {
149 my ($self, $by, $value) = @_;
150  
151 my $user;
152 if ($by eq 'id') {
153 my $res = $self->_cached("api.users.info:user=$value", sub {
154 $self->api->users->info(user => $value);
155 });
156 $user = $res->{user} if $res->{ok};
157 }
158 elsif ($by eq 'name') {
159 my $list = $self->_cached("api.users.list", sub { $self->api->users->list });
160 if ($list->{ok}) {
161 ($user) = grep { $_->{name} eq $value } @{ $list->{members} };
162 }
163 }
164 else {
165 croak "unknown lookup type $by";
166 }
167  
168 if (defined $user) {
169 return Bot::Backbone::Identity->new(
170 username => $user->{id},
171 nickname => $user->{name},
172 me => ($user->{id} eq $self->user_id),
173 );
174 }
175 else {
176 croak "unknown user $by $value";
177 }
178 }
179  
180  
181 sub load_me {
182 my $self = shift;
183 return $self->load_user(id => $self->user_id);
184 }
185  
186  
187 sub load_user_channel {
188 my ($self, $by, $value) = @_;
189  
190 croak "unknown lookup type $by" unless $by eq 'user' or $by eq 'id';
191  
192 my $list = $self->_cached("api.im.list", sub { $self->api->im->list });
193  
194 croak "unknown IM $by $value" unless $list->{ok};
195  
196 my ($im) = grep { $_->{ $by } eq $value } @{ $list->{members} };
197 return $im->{id};
198 }
199  
200 # Initially, I thought this method would be necessary. Now I'm thinking
201 # it's completely unnecessary. As such, I don't want to document it for now.
202 sub load_channel {
203 my ($self, $by, $value) = @_;
204  
205 # It really has to be by ID since we collapse group/channel notions
206 croak "unknown lookup type $by" unless $by eq 'id';
207  
208 my $group;
209 my $type = substr $value, 0, 1;
210 if ($type eq 'G') {
211 # TODO When this method is added, bring it back..
212 # See https://github.com/mihyaeru21/p5-WebService-Slack-WebApi/issues/4
213 #my $res = $self->api->groups->info( channel => $value );
214 #$group = $res->{group} if $res->{ok};
215 my $res = $self->_cached("api.groups.list", sub { $self->api->groups->list });
216 if ($res->{ok}) {
217 ($group) = grep { $_->{ $by } eq $value } @{ $res->{groups} };
218 }
219 }
220 elsif ($type eq 'C') {
221 my $res = $self->_cached("api.channels.info:channel=$value", sub {
222 $self->api->channels->info( channel => $value )
223 });
224 $group = $res->{channel} if $res->{ok};
225 }
226 else {
227 croak "unknown group type $type";
228 }
229  
230 if (defined $group) {
231 return $group->{id};
232 }
233 else {
234 croak "cannot find group $by $value";
235 }
236 }
237  
238  
239 sub join_group {
240 my ($self, $options) = @_;
241  
242 my $type = substr $options->{group}, 0, 1;
243  
244 if ($type eq 'G') {
245 $self->api->groups->open(channel => $options->{group});
246 }
247 elsif ($type eq 'C') {
248 $self->api->channels->join(name => $options->{group});
249 }
250 else {
251 croak "unknown group type $type";
252 }
253 }
254  
255  
256 sub got_message {
257 my ($self, $rtm, $slack_msg) = @_;
258  
259 # Mark every message as read as it comes
260 $self->mark_read($slack_msg);
261  
262 # Ignore messages with a subtype
263 return if defined $slack_msg->{subtype};
264  
265 # Ignore message edits
266 return if defined $slack_msg->{edited};
267  
268 # We need to determine the channel type
269 my $channel_type = substr $slack_msg->{channel}, 0, 1;
270  
271 # IDs for Slack identify type by starting char:
272 #
273 # D - IM channel
274 # G - Private Group channel
275 # C - Team channel
276 #
277  
278 if ($channel_type eq 'D') {
279 $self->got_direct_message($slack_msg);
280 }
281 else {
282 $self->got_group_message($slack_msg);
283 }
284 }
285  
286  
287 sub got_direct_message {
288 my ($self, $slack_msg) = @_;
289  
290 # Ignore messages from ourself
291 return if $slack_msg->{user} eq $self->whoami->{user_id};
292  
293 my $message = Bot::Backbone::Message->new({
294 chat => $self,
295 from => $self->load_user(id => $slack_msg->{user}),
296 to => $self->load_user(id => $self->user_id),
297 group => undef,
298 text => $slack_msg->{text},
299 });
300  
301 $self->resend_message($message);
302 $self->dispatch_message($message);
303 }
304  
305  
306 sub is_to_me {
307 my ($self, $me_user, $text) = @_;
308  
309 my $me_nick = $me_user->nickname;
310 return scalar($$text =~ s/^ @?$me_nick \s* [:,\-] \s*
311 | \s* , \s* @?$me_nick [.!?]? $
312 | , \s* @?$me_nick \s* ,
313 //x);
314 }
315  
316 # Not sure I like how this works yet. Leaving out of the docs for now.
317 sub mark_read {
318 my ($self, $slack_msg) = @_;
319  
320 # Don't really mark more than every 15 seconds
321 return unless time - $self->last_mark > 15;
322  
323 my $channel = $slack_msg->{channel};
324 my $ts = $slack_msg->{ts};
325  
326 my $type = substr $channel, 0, 1;
327 if ($type eq 'C') {
328 $self->api->channels->mark( channel => $channel, ts => $ts );
329 }
330 elsif ($type eq 'G') {
331 $self->api->groups->mark( channel => $channel, ts => $ts );
332 }
333 elsif ($type eq 'D') {
334 $self->api->im->mark( channel => $channel, ts => $ts );
335 }
336  
337 $self->last_mark(time);
338 }
339  
340  
341 sub got_group_message {
342 my ($self, $slack_msg) = @_;
343  
344 # Ignore messages from ourself
345 return if $slack_msg->{user} eq $self->whoami->{user_id};
346  
347 my $me_user = $self->load_me;
348  
349 my $text = $slack_msg->{text};
350 my $to_identity;
351 if ($self->is_to_me($me_user, \$text)) {
352 $to_identity = $me_user;
353 }
354  
355 my $message = Bot::Backbone::Message->new({
356 chat => $self,
357 from => $self->load_user(id => $slack_msg->{user}),
358 to => $to_identity,
359 group => $self->load_channel( id => $slack_msg->{channel} ),
360 text => $text,
361 });
362  
363 $self->resend_message($message);
364 $self->dispatch_message($message);
365 }
366  
367  
368 sub send_message {
369 my ($self, $params) = @_;
370  
371 my $to = $params->{to};
372 my $group = $params->{group};
373 my $text = $params->{text};
374 my $attachments = $params->{attachments};
375  
376 my $channel;
377 if (defined $group) {
378 $channel = $self->load_channel( id => $group );
379 }
380 else {
381 $channel = $self->load_user_channel( user => $to );
382 }
383  
384 my %message_opts = (
385 channel => $channel,
386 as_user => 1,
387 );
388 if (defined $text) {
389 $message_opts{text} = encode('utf8', $text);
390 }
391 if (defined $attachments) {
392 $message_opts{attachments} = $attachments;
393 }
394  
395 $self->api->chat->post_message(%message_opts);
396 }
397  
398  
399 __PACKAGE__->meta->make_immutable;
400  
401 __END__
402  
403 =pod
404  
405 =encoding UTF-8
406  
407 =head1 NAME
408  
409 Bot::Backbone::Service::SlackChat - Connect and chat with a Slack server
410  
411 =head1 VERSION
412  
413 version 0.161740
414  
415 =head1 SYNOPSIS
416  
417 package MyBot;
418 use Bot::Backbone;
419  
420 service slack_chat => (
421 service => 'SlackChat',
422 token => '...', # see slack.com for your tokens
423 );
424  
425 service dice => (
426 service => 'OFun::Dice',
427 );
428  
429 service "general_chat" => (
430 service => 'GroupChat',
431 chat => 'SlackChat',
432 group => 'C',
433 dispatcher => 'general_dispatch',
434 );
435  
436 dispatcher 'general_dispatch' => as {
437 redispatch_to "dice";
438 };
439  
440 __PACKAGE__->new->run;
441  
442 =head1 DESCRIPTION
443  
444 This allows a L<Bot::Backbone> chat bot to be connect to a Slack server using their Real-Time Messaging API.
445  
446 This is based on L<AnyEvent::SlackRTM> and L<WebService::Slack::WebApi>. It also uses a L<CHI> cache to help avoid contacting the Slack server too often, which could result in your bot becoming rate limited.
447  
448 =head1 ATTRIBUTES
449  
450 =head2 token
451  
452 The C<token> is the access token from Slack to use. This may be either of the following type of tokens:
453  
454 =over
455  
456 =item *
457  
458 L<User Token|https://api.slack.com/tokens>. This is a token to perform actions on behalf of a user account.
459  
460 =item *
461  
462 L<Bot Token|https://slack.com/services/new/bot>. If you configure a bot integration, you may use the access token on the bot configuration page to use this library to act on behalf of the bot account. Bot accounts may not have the same features as a user account, so please be sure to read the Slack documentation to understand any differences or limitations.
463  
464 =back
465  
466 Which you use will depend on whether you want the bot to control a user account or a bot integration account. You are responsible for adhering to the Slack terms of use in whatever you do.
467  
468 =head2 cache
469  
470 This is a L<CHI> cache to use to temporarily store response from the Slack APIs. By default, this is a memory-only cache that caches data for only 60 seconds. The purpose is mainly to prevent repeated requests to the API, which might result in rate limiting.
471  
472 =head2 api
473  
474 This is the L<WebService::Slack::WebApi> object used to contact Slack for information about channels, users, etc.
475  
476 =head2 rtm
477  
478 This is the L<AnyEvent::SlackRTM> object used to communicate with Slack and trigger events from the Real-Time Messaging API.
479  
480 =head2 error_callback
481  
482 This is a callback sub that may be used to report error events from the RTM API. Set it to a sub that will be called as follows:
483  
484 sub {
485 my ($self, $rtm, $message) = @_;
486  
487 ...
488 }
489  
490 Here, C<$self> is the L<Bot::Backbone::Service::SlackChat> object, C<$rtm> is the L<AnyEvent::SlackRTM> object, and C<$message> is a hash containing the error message, as described on the L<Real Time Messaging API|https://api.slack.com/rtm> documentation.
491  
492 =head2 whoami
493  
494 This returns a hash containing information about who the bot is.
495  
496 =head1 METHODS
497  
498 =head2 user
499  
500 Returns the name of the bot.
501  
502 =head2 user_id
503  
504 Returns the user ID for the bot.
505  
506 =head2 team_id
507  
508 Returns the team ID for the team account.
509  
510 =head2 initialize
511  
512 This connects to Slack and prepares the bot for communication.
513  
514 =head2 load_user
515  
516 method load_user($by, $value) returns Bot::Backbone::Identity
517  
518 Fetches information about a user from Slack and returns the user as a L<Bot::Backbone::Identity>. The C<$by> setting determines how the user is looked up, which may either be by "id" or by "name". The value, then, is the value to check.
519  
520 =head2 load_me
521  
522 method load_me() returns Bot::Backbone::Identity
523  
524 Returns the identity object for the bot itself.
525  
526 =head2 load_user_channel
527  
528 method load_user_channel($by, $value) returns Str
529  
530 Returns the ID of a user's IM channel. Here C<$by> may be "user" to lookup by user ID.
531  
532 =head2 join_group
533  
534 method join_group({ group => $group })
535  
536 Given the ID of a channel or group, this causes the bot to open or join it. Note that Slack bot integration accounts might not be able to join team channels, but may still be invited.
537  
538 =head2 got_message
539  
540 Handles messages from Slack. Decides whether they are group messages or direct and forwards them on as appropriate. Messages with a "subtype" will be ignored as will messages that are "edited".
541  
542 This method also marks messages as read.
543  
544 =head2 got_direct_message
545  
546 Handles direct messages received from an IM channel.
547  
548 =head2 is_to_me
549  
550 This determines whether or not the message is to the bot.
551  
552 =head2 got_group_message
553  
554 This handles message received from private group or team channels.
555  
556 =head2 send_message
557  
558 method send_message({
559 to => $user_id,
560 group => $group_id,
561 text => $message,
562 attachments => $attachments,
563 })
564  
565 This sends a message to a Slack channel. To the named user's IM channel or to a private group or team channel named by C<$group_id>. Attachments can be included to produce formatted messages.
566  
567 L<Slack Message Attachment API|https://api.slack.com/docs/attachments>
568  
569 =for Pod::Coverage load_channel
570 mark_read
571  
572 =head1 AUTHOR
573  
574 Andrew Sterling Hanenkamp <hanenkamp@cpan.org>
575  
576 =head1 COPYRIGHT AND LICENSE
577  
578 This software is copyright (c) 2016 by Qubling Software LLC.
579  
580 This is free software; you can redistribute it and/or modify it under
581 the same terms as the Perl 5 programming language system itself.
582  
583 =cut