Discord.pm 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package Cpanel::iContact::Provider::Discord;
  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::Discord - Backend for the Discord iContact module
  9. =head1 SYNOPSIS
  10. use Cpanel::iContact::Provider::Discord;
  11. my $notifier = Cpanel::iContact::Provider::Discord->new();
  12. $notifier->send();
  13. =head1 DESCRIPTION
  14. Provide backend accessor for the Discord iContact module.
  15. =cut
  16. =head2 send
  17. Sends off the notification over to your Discord 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 @errs;
  34. require Cpanel::HTTP::Client;
  35. my $ua = Cpanel::HTTP::Client->new( 'default_headers' => { 'content-type' => 'application/json' } )->die_on_http_error();
  36. my $subject = $args_hr->{'subject'};
  37. my $message = ${ $args_hr->{'text_body'} };
  38. require Cpanel::AdminBin::Serializer;
  39. # GitHub issue #18 -- Discord max message length is 2000 chars.
  40. # As such , truncate at 1996, add ellipsis (3 chars).
  41. # Why not 1997? I want to avoid fencepost errors.
  42. my $message_json = Cpanel::AdminBin::Serializer::Dump(
  43. {
  44. 'content' => substr( "$subject\n\n$message", 0, 1996 ) . "...",
  45. }
  46. );
  47. # Send it
  48. foreach my $destination ( @{ $args_hr->{'to'} } ) {
  49. try {
  50. my $res = $ua->request( 'POST', $destination, { 'content' => $message_json } );
  51. die( sprintf "Error %d: %s", $res->status(), $res->reason() ) if !$res->success();
  52. }
  53. catch {
  54. require Cpanel::Exception;
  55. push(
  56. @errs,
  57. Cpanel::Exception::create(
  58. 'ConnectionFailed',
  59. 'The system failed to send the message to “[_1]” due to an error: [_2]',
  60. [ $destination, $_ ]
  61. )
  62. );
  63. };
  64. }
  65. if (@errs) {
  66. # Module should already be loaded above
  67. die Cpanel::Exception::create( 'Collection', [ exceptions => \@errs ] );
  68. }
  69. return 1;
  70. }
  71. 1;