Telegram.pm 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package Cpanel::iContact::Provider::Telegram;
  2. use strict;
  3. use warnings;
  4. use parent 'Cpanel::iContact::Provider';
  5. use Try::Tiny;
  6. =encoding utf-8
  7. =head1 NAME
  8. Cpanel::iContact::Provider::Telegram - Backend for the Telegram iContact module
  9. =head1 SYNOPSIS
  10. use Cpanel::iContact::Provider::Telegram;
  11. my $notifier = Cpanel::iContact::Provider::Telegram->new();
  12. $notifier->send();
  13. =head1 DESCRIPTION
  14. Provide backend accessor for the Telegram iContact module.
  15. =cut
  16. =head2 send
  17. Sends off the notification over to your Telegram channel/user
  18. =over 2
  19. =item Input
  20. =over 3
  21. None
  22. =back
  23. =item Output
  24. =over 3
  25. Truthy value on success, exception on failure.
  26. =back
  27. =back
  28. =cut
  29. sub send {
  30. my ($self) = @_;
  31. my $args_hr = $self->{'args'};
  32. my $contact_hr = $self->{'contact'};
  33. my @missing = grep { !defined $self->{'contact'}{$_} } qw{TELEGRAMBOTTOKEN};
  34. die "Kit not complete! Missing: " . join( ", ", @missing ) if scalar( @missing );
  35. my @errs;
  36. require WWW::Telegram::BotAPI;
  37. my $api = WWW::Telegram::BotAPI->new(
  38. token => $self->{'contact'}{'TELEGRAMBOTTOKEN'},
  39. );
  40. # Test the auth. Will die if it fails.
  41. $api->getMe();
  42. # Telegram max message length is 4096 chars.
  43. # As such , truncate at 4092, add ellipsis (3 chars).
  44. # Why not 4093? I want to avoid fencepost errors.
  45. my $message = substr( $args_hr->{'subject'} . "\n" . ${$args_hr->{'text_body'}}, 0, 4092 );
  46. $message .= '...' if length $message == 4092;
  47. # Send it
  48. foreach my $destination ( @{ $args_hr->{'to'} } ) {
  49. try {
  50. $api->sendMessage({
  51. 'chat_id' => $destination,
  52. 'text' => $message,
  53. });
  54. }
  55. catch {
  56. require Cpanel::Exception;
  57. push(
  58. @errs,
  59. Cpanel::Exception::create(
  60. 'ConnectionFailed',
  61. 'The system failed to send the message to “[_1]” due to an error: [_2]',
  62. [ $destination, $_ ]
  63. )
  64. );
  65. };
  66. }
  67. if (@errs) {
  68. use Data::Dumper;
  69. print Dumper(\@errs);
  70. # Module should already be loaded above
  71. die Cpanel::Exception::create( 'Collection', [ exceptions => \@errs ] );
  72. }
  73. return 1;
  74. }
  75. 1;