Skip to content

Commit

Permalink
Fix cases where xkcd image URL returns non-200 status soon after release
Browse files Browse the repository at this point in the history
  • Loading branch information
tulir committed Sep 30, 2021
1 parent 9ac26de commit cee2b93
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions xkcd.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ def get_latest_xkcd(self) -> Awaitable[XKCDInfo]:
def get_xkcd(self, num: int) -> Awaitable[XKCDInfo]:
return self._get_xkcd_info(f"https://xkcd.com/{num}/info.0.json")

async def _get_media_info(self, image_url: str) -> MediaCache:
async def _get_media_info(self, image_url: str) -> Optional[MediaCache]:
cache = self.media_cache.query.get(image_url)
if cache is not None:
return cache
Expand All @@ -213,6 +213,10 @@ async def _get_media_info(self, image_url: str) -> MediaCache:
self.db.add(cache)
self.db.commit()
return cache
else:
self.log.error(f"Getting media info for {image_url} returned {resp.status}: "
f"{await resp.text()}")
return None

async def send_xkcd(self, room_id: RoomID, xkcd: XKCDInfo) -> None:
try:
Expand All @@ -222,6 +226,8 @@ async def send_xkcd(self, room_id: RoomID, xkcd: XKCDInfo) -> None:

async def _send_xkcd(self, room_id: RoomID, xkcd: XKCDInfo) -> None:
info = await self._get_media_info(xkcd.img)
if not info:
return
if self.config["inline"]:
content = TextMessageEventContent(
msgtype=MessageType.TEXT, format=Format.HTML,
Expand Down Expand Up @@ -283,8 +289,10 @@ async def _poll_xkcd(self) -> None:
except Exception:
self.log.exception("Failed to get latest xkcd")
if latest.num > self.latest_id:
self.latest_id = latest.num
await self.broadcast(latest)
info = await self._get_media_info(latest.img)
if info:
self.latest_id = latest.num
await self.broadcast(latest)
await asyncio.sleep(self.config["poll_interval"], loop=self.loop)

@command.new(name=lambda self: self.config["base_command"],
Expand Down

0 comments on commit cee2b93

Please sign in to comment.