From dfe27f0cba5d9c28cbc54045a9bf0f9b8a546912 Mon Sep 17 00:00:00 2001 From: PredaaA <46051820+PredaaA@users.noreply.github.com> Date: Sun, 24 Oct 2021 19:02:55 +0200 Subject: [PATCH] [DadJokes] Handle aiohttp errors and non 200 status code (#253) --- dadjokes/dadjokes.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/dadjokes/dadjokes.py b/dadjokes/dadjokes.py index f250ed7..7ffadd5 100644 --- a/dadjokes/dadjokes.py +++ b/dadjokes/dadjokes.py @@ -15,7 +15,12 @@ class DadJokes(commands.Cog): @commands.command() async def dadjoke(self, ctx): """Gets a random dad joke.""" - api = "https://icanhazdadjoke.com/" - async with aiohttp.request("GET", api, headers={"Accept": "text/plain"}) as r: - result = await r.text(encoding="UTF-8") - await ctx.send(f"`{result}`") + try: + async with aiohttp.request("GET", "https://icanhazdadjoke.com/", headers={"Accept": "text/plain"}) as r: + if r.status != 200: + return await ctx.send("Oops! Cannot get a dad joke...") + result = await r.text(encoding="UTF-8") + except aiohttp.ClientConnectionError: + return await ctx.send("Oops! Cannot get a dad joke...") + + await ctx.send(f"`{result}`")