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