Yuriy Zhilovets 4 years ago
parent
commit
1e7faa59d4
1 changed files with 35 additions and 8 deletions
  1. 35 8
      telegram.pl

+ 35 - 8
telegram.pl

@@ -13,7 +13,7 @@ use AnyEvent;
 use Mojolicious::Lite;
 use Mojo::UserAgent;
 use Data::Dumper;
-use Promises qw/deferred/;
+use Promises qw/deferred collect/;
 use Mojo::JSON qw/j/;
 use NetAddr::IP;
 
@@ -184,8 +184,33 @@ sub incoming_message
   eval {
     $res = $sub->($body,$m);
   };
+  
+  if (ref $res eq "Promises::Promise")
+  {
+    $res->then(sub
+    {
+      my $result = shift;
+      handle_reply($m, undef, $result);
+    })
+    ->catch(sub
+    {
+      my $err = shift;
+      handle_reply($m, $err, undef);
+    })
+  }
+  else
+  {
+    handle_reply($m, $@, $res);
+  }
+}
 
-  if ($@)
+sub handle_reply
+{
+  my $m = shift;
+  my $err = shift;
+  my $res = shift;
+
+  if ($err)
   {
     $log->error(Dumper $@);
     $rabbit->reply($m, $@) if $m->{header}->{reply_to};
@@ -208,21 +233,23 @@ sub notify::telegram::send
   
   my @results;
   
-  foreach (@$to)
-  {
+  my @promises = map {
     notify($_, $body->{message}, $body)->then(sub
     {
       my $reply = shift;
-      push @results, { success=>1, msgid=>$reply->{result}->{message_id}, chat=>$reply->{chat}->{id} };
+      push @results, { success=>1, msgid=>$reply->{result}->{message_id}, chat=>$reply->{result}->{chat}->{id} };
     })
     ->catch(sub
     {
       my $reply = shift;
       push @results, {success=>0, error => ref($reply) ? "$reply->{code}: $reply->{body}->{description}" : $reply};
     })
-  }
-  
-  return \@results;
+  } @$to;
+
+  return collect(@promises)->then(sub
+  {
+    return \@results;
+  })
 }
 
 ############################