Net-Mattermost-Bot
view release on metacpan or search on metacpan
lib/Net/Mattermost/Bot.pm view on Meta::CPAN
package Net::Mattermost::Bot;
use 5.6.1;
use Carp qw(carp croak);
use Furl;
use HTTP::Status ':is';
use JSON::MaybeXS qw(encode_json decode_json);
use List::Util 'pairs';
use Mojo::IOLoop;
use Mojo::UserAgent;
use Moo;
use MooX::HandlesVia;
use Types::Standard qw(ArrayRef Bool HashRef Int Object Str);
our $VERSION = '0.04';
################################################################################
has base_url => (is => 'ro', isa => Str, required => 1);
has team_name => (is => 'ro', isa => Str, required => 1);
has username => (is => 'ro', isa => Str, required => 1);
has password => (is => 'ro', isa => Str, required => 1);
has debug => (is => 'ro', isa => Bool, default => 0);
has ping_interval => (is => 'ro', isa => Int, default => 15);
has ssl_opts => (is => 'ro', isa => HashRef, default => sub { {} });
has token => (is => 'rw', isa => Str, default => '');
has user_id => (is => 'rw', isa => Str, default => '');
has api_url => (is => 'ro', isa => Str, lazy => 1, builder => '_build_api_url');
has endpoints => (is => 'ro', isa => HashRef, lazy => 1, builder => '_build_endpoints');
has furl => (is => 'ro', isa => Object, lazy => 1, builder => '_build_furl');
has headers => (is => 'rw', isa => ArrayRef, lazy => 1, builder => '_build_headers',
handles_via => 'Array',
handles => { add_header => 'push' });
has ws_url => (is => 'ro', isa => Str, lazy => 1, builder => '_build_ws_url');
################################################################################
sub connect {
my $self = shift;
my $login_endpoint = sprintf('%s/users/login', $self->api_url);
my $init = $self->furl->post($login_endpoint, $self->headers, encode_json({
name => $self->team_name,
login_id => $self->username,
password => $self->password,
}));
my $out = decode_json($init->{content});
if ($out->{status_code} && !is_success($init->{status_code})) {
croak $out->{message};
}
if ($init->header('Token')) {
$self->token($init->header('Token'));
$self->user_id($out->{id});
$self->add_header(
Cookie => sprintf('MMAUTHTOKEN=%s', $self->token),
Authorization => sprintf('Bearer %s', $self->token),
'Keep-Alive' => 1,
);
} else {
croak 'Unauthorized';
}
$self->event_connected();
$self->_start();
return 1;
}
sub handle_message {
my $self = shift;
my $content = shift;
# Filter out empty responses and messages from ourself
return unless $content && $content->{event};
if ($content->{data}->{post}) {
my $post_data = decode_json($content->{data}->{post});
return if $post_data->{user_id} eq $self->user_id;
}
my $output;
if ($content->{event} eq 'hello') {
if ($self->debug) {
( run in 1.613 second using v1.01-cache-2.11-cpan-39bf76dae61 )