App-RoboBot

 view release on metacpan or  search on metacpan

lib/App/RoboBot/Network/Slack.pm  view on Meta::CPAN


use App::RoboBot::Channel;
use App::RoboBot::Message;
use App::RoboBot::Nick;

extends 'App::RoboBot::Network';

has '+type' => (
    default => 'slack',
);

has 'token' => (
    is       => 'ro',
    isa      => 'Str',
    required => 1,
);

has 'client' => (
    is     => 'rw',
    isa    => 'AnyEvent::SlackRTM',
    traits => [qw( SetOnce )],
);

has 'keepalive' => (
    is     => 'rw',
    traits => [qw( SetOnce )],
);

has 'ping_payload' => (
    is      => 'ro',
    isa     => 'HashRef',
    default => sub { { pong => 1 } },
);

has 'start_ts' => (
    is      => 'ro',
    isa     => 'Int',
    default => sub { time() },
);

has 'profile_cache' => (
    is      => 'rw',
    isa     => 'HashRef',
    default => sub { {} },
);

has 'channel_cache' => (
    is      => 'rw',
    isa     => 'HashRef',
    default => sub { {} },
);

sub BUILD {
    my ($self) = @_;

    $self->client(AnyEvent::SlackRTM->new(
        $self->token
    ));

    $self->client->on( 'hello' => sub {
        $self->keepalive(AnyEvent->timer(
            interval => 60,
            cb       => sub { $self->reconnect if $self->client->finished }
        ));
    });

    $self->client->on( 'message' => sub {
        my ($cl, $msg) = @_;
        $self->handle_message($msg);
    });
}

sub connect {
    my ($self) = @_;

    $self->log->info(sprintf('Connecting to Slack network %s.', $self->name));

    # Build our channel list so that things like channel linking will work.
    my $res = $self->bot->config->db->do(q{
        select id, name
        from channels
        where network_id = ?
        order by name asc
    }, $self->id);

    return unless $res;

    my @channels;

    while ($res->next) {
        # Do not include Slack DMs in the channel list.
        next if $res->{'name'} =~ m{^dm:};
        push(@channels, App::RoboBot::Channel->find_by_id($self->bot, $res->{'id'}));
    }

    $self->channels(\@channels);

    $self->log->debug('Channels loaded.');

    # Callbacks should be registered already in the BUILD method, so we just
    # need to start the client and have it connect to the Slack WebSocket API.
    $self->client->start;

    $self->log->debug('SlackRTM client started.');
}

sub disconnect {
    my ($self) = @_;

    $self->client->close;
}

sub reconnect {
    my ($self) = @_;

    $self->disconnect && $self->connect;
}

sub send {
    my ($self, $response) = @_;



( run in 2.083 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )