From 861d4b51adc878edb1d7279eb7f34e5b90b18856 Mon Sep 17 00:00:00 2001 From: Daniel Muckerman Date: Sat, 6 Jan 2018 21:38:15 -0500 Subject: [PATCH] Attempt to rescue and fallback to og:image url if extracted pixiv image doesn't resolve properly --- slack-pixiv/commands/illust.rb | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/slack-pixiv/commands/illust.rb b/slack-pixiv/commands/illust.rb index fb4bc44..566ebdf 100644 --- a/slack-pixiv/commands/illust.rb +++ b/slack-pixiv/commands/illust.rb @@ -18,10 +18,10 @@ module SlackMathbot puts pixiv_url # Create iOS Illustration URL, regex pixiv_url to - # extract numbers only, such as /^[0-9]+$/ + # extract numbers only, such as /^[0-9]+$/ #ios_url = "pixiv://illusts/" + pixiv_url.split("illust_id=")[-1] - ios_url = "pixiv://illusts/" + pixiv_url[/\d+/] - puts ios_url + ios_url = "pixiv://illusts/" + pixiv_url[/\d+/] + puts ios_url # Scrape profile link profile = agent.get(pixiv_url).at("div.userdata-row > h2.name > a").attributes['href'].to_s @@ -37,6 +37,23 @@ module SlackMathbot # Scrape image image_url = agent.get(pixiv_url).images_with(:src => /600x600\/img-master/)[0].to_s.sub! '600x600','480x960' + begin + # Attempt to check on image + page = agent.head(image_url) + + # Make sure page came back kosher + if page.code.to_i == 200 + # Image url is fine + puts "Image is good to go!" + else + # Fallback on http error to be safe + image_url = "https://embed.pixiv.net/decorate.php?illust_id=" + pixiv_url[/\d+/] + end + rescue Mechanize::ResponseCodeError + # Fallback to og:image url + puts "Image failed to load" + image_url = "https://embed.pixiv.net/decorate.php?illust_id=" + pixiv_url[/\d+/] + end puts image_url client.web_client.chat_postMessage(