DoctorKarma/lib/DoctorKarma/Telegram.pm

158 lines
3.6 KiB
Perl

package DoctorKarma::Telegram;
use v5.30.0;
use strict;
use warnings;
use Types::Standard qw/Str Int Ref/;
use Params::ValidationCompiler qw(validation_for);
use Mojo::UserAgent;
use JSON;
use DoctorKarma::Logger;
{
my $validator = validation_for(
params => {
telegram_token => { type => Str },
}
);
sub new {
my $class = shift;
my $self = bless {}, $class;
my %params = $validator->(@_);
my $telegram_token = $params{telegram_token};
$self->{telegram_token} = $telegram_token;
return $self;
}
}
sub _logger {
my $self = shift;
if ( !defined $self->{logger} ) {
$self->{logger} = DoctorKarma::Logger->new;
}
return $self->{logger};
}
sub _user_agent {
my $self = shift;
if ( !defined $self->{user_agent} ) {
$self->{user_agent} = Mojo::UserAgent->new;
}
return $self->{user_agent};
}
{
my $validator = validation_for(
params => {
method => { type => Str },
body => { type => Ref },
}
);
sub _request {
my $self = shift;
my %params = $validator->(@_);
my $method = $params{method};
my $body = $params{body};
my $ua = $self->_user_agent;
my $logger = $self->_logger;
my $url = $self->_generate_url( method => $method );
my $response =
decode_json( $ua->post( $url => {} => json => $body )->result->body );
unless ( $response->{ok} ) {
$logger->log_critical( $response->{description} );
}
return $response;
}
}
{
my $validator = validation_for(
params => {
chat_id => { type => Int },
text => { type => Str },
}
);
sub send_message {
my $self = shift;
my %params = $validator->(@_);
my $chat_id = $params{chat_id};
my $text = $params{text};
my $response = $self->_request(
method => q/sendMessage/,
body => {
chat_id => $chat_id,
text => $text,
parse_mode => 'MarkdownV2',
}
);
return $response->{result};
}
}
sub get_updates {
my $self = shift;
my $last_update = $self->_last_update;
if ( !defined $last_update ) {
$last_update = 0;
}
my $response = $self->_request(
method => q/getUpdates/,
body => { offset => $last_update + 1 }
);
if ( scalar $response->{result}->@* ) {
$last_update = $response->{result}[-1]{update_id};
$self->_set_last_update($last_update);
}
return $response->{result};
}
{
my $validator = validation_for(
params => {
method => { type => Str },
}
);
sub _generate_url {
my $self = shift;
my %params = $validator->(@_);
my $method = $params{method};
my $telegram_token = $self->_telegram_token;
my $url = qq(https://api.telegram.org/bot$telegram_token/$method);
return $url;
}
}
{
my $validator = validation_for( params => [ { type => Int } ] );
sub _set_last_update {
my $self = shift;
my ($last_update) = $validator->(@_);
$self->{last_update} = $last_update;
}
}
sub _last_update {
my $self = shift;
if ( !exists $self->{last_update} ) {
return undef;
}
return $self->{last_update};
}
sub _telegram_token {
my $self = shift;
return $self->{telegram_token};
}
1;