From 3c721b905fdde3331c26cce9be67b3c090a659eb Mon Sep 17 00:00:00 2001 From: eleksir Date: Thu, 22 Apr 2021 18:40:46 +0300 Subject: [PATCH] Sometimes xkcd.ru returns redirect to 404, retry to get correct content in this case. --- lib/BotLib/Xkcd.pm | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/lib/BotLib/Xkcd.pm b/lib/BotLib/Xkcd.pm index 31b909a..52dea77 100644 --- a/lib/BotLib/Xkcd.pm +++ b/lib/BotLib/Xkcd.pm @@ -13,15 +13,30 @@ our @EXPORT_OK = qw (Xkcd); sub Xkcd { my $ua = Mojo::UserAgent->new->connect_timeout (5)->max_redirects (0); - my $r = $ua->get ('https://xkcd.ru/random/')->result; + my $location; + my $status = 400; + my $c = 0; - if ( - defined $r->content && - defined $r->content->headers && - defined $r->content->headers->location && - $r->content->headers->location ne '' - ) { - return sprintf '[xkcd.ru](https://xkcd.ru/i/%s_v1.png)', substr ($r->content->headers->location, 1, -1); + do { + my $r = $ua->get ('https://xkcd.ru/random/')->result; + + if ( + defined $r->content && + defined $r->content->headers && + defined $r->content->headers->location && + $r->content->headers->location ne '' + ) { + $location = substr $r->content->headers->location, 1, -1; + $location = sprintf 'https://xkcd.ru/i/%s_v1.png', $location; + $r = $ua->head ($location)->result; + } + + $c++; + $status = $r->code; + } while ($c < 3 || $status >= 404); + + if ($status == 200) { + return sprintf '[xkcd.ru](%s)', $location; } return 'Комикс-стрип нарисовать не так-то просто :(';