fix(bible): fixing error handling

This commit is contained in:
Seaswimmer 2024-02-01 19:46:39 -05:00
parent 6df92da12f
commit 2841fb12a5
Signed by untrusted user: cswimr
GPG key ID: B8953EC01E5C4063
2 changed files with 70 additions and 61 deletions

View file

@ -44,7 +44,7 @@ class Bible(commands.Cog):
for book in books:
if book_name in (book["abbreviation"], book["name"]):
return book["id"]
raise ValueError(f"Book {book_name} not found.")
raise ValueError(error(f"Book {book_name} not found."))
async def _get_passage(
self, bible_id: str, passage_id: str, include_verse_numbers: bool
@ -67,13 +67,11 @@ class Bible(commands.Cog):
"_get_passage executed with a response code of: %s", response.status
)
if response.status == 401:
raise bible.errors.Unauthorized("Missing/Invalid API key.")
raise bible.errors.Unauthorized()
if response.status == 403:
raise bible.errors.BibleAccessError(
"The provided API key cannot retrieve sections from the configured Bible."
)
raise bible.errors.BibleAccessError()
if response.status == 404:
raise bible.errors.NotFound("The requested passage was not found.")
raise bible.errors.NotFound()
data = await response.json()
return data["data"]
@ -87,11 +85,9 @@ class Bible(commands.Cog):
"_get_books executed with a response code of: %s", response.status
)
if response.status == 401:
raise bible.errors.Unauthorized("Missing/Invalid API key.")
raise bible.errors.Unauthorized()
if response.status == 403:
raise bible.errors.BibleAccessError(
"The provided API key cannot retrieve sections from the configured Bible."
)
raise bible.errors.BibleAccessError()
data = await response.json()
return data["data"]
@ -105,11 +101,9 @@ class Bible(commands.Cog):
"_get_chapters executed with a response code of: %s", response.status
)
if response.status == 401:
raise bible.errors.Unauthorized("Missing/Invalid API key.")
raise bible.errors.Unauthorized()
if response.status == 403:
raise bible.errors.BibleAccessError(
"The provided API key cannot retrieve sections from the configured Bible."
)
raise bible.errors.BibleAccessError()
data = await response.json()
return data["data"]
@ -123,11 +117,9 @@ class Bible(commands.Cog):
"_get_verses executed with a response code of: %s", response.status
)
if response.status == 401:
raise bible.errors.Unauthorized("Missing/Invalid API key.")
raise bible.errors.Unauthorized()
if response.status == 403:
raise bible.errors.BibleAccessError(
"The provided API key cannot retrieve sections from the configured Bible."
)
raise bible.errors.BibleAccessError()
data = await response.json()
return data["data"]
@ -150,17 +142,25 @@ class Bible(commands.Cog):
await ctx.send(str(e))
return
if len(passage.split("-")) == 2:
from_verse, to_verse = passage.replace(":", ".").split("-")
if "." not in to_verse:
to_verse = f"{from_verse.split('.')[0]}.{to_verse}"
passage = await self._get_passage(
bible_id, f"{book_id}.{from_verse}-{book_id}.{to_verse}", True
)
else:
passage = await self._get_passage(
bible_id, f"{book_id}.{passage.replace(':', '.')}", False
)
try:
if len(passage.split("-")) == 2:
from_verse, to_verse = passage.replace(":", ".").split("-")
if "." not in to_verse:
to_verse = f"{from_verse.split('.')[0]}.{to_verse}"
passage = await self._get_passage(
bible_id, f"{book_id}.{from_verse}-{book_id}.{to_verse}", True
)
else:
passage = await self._get_passage(
bible_id, f"{book_id}.{passage.replace(':', '.')}", False
)
except (
bible.errors.BibleAccessError,
bible.errors.NotFound,
bible.errors.Unauthorized,
) as e:
await ctx.send(e.message)
return
if len(passage["content"]) > 4096:
await ctx.send("The passage is too long to send.")
@ -179,16 +179,24 @@ class Bible(commands.Cog):
"""Get a random Bible verse."""
bible_id = await self.config.bible()
books = await self._get_books(bible_id)
book = random.choice(books)
try:
books = await self._get_books(bible_id)
book = random.choice(books)
chapters = await self._get_chapters(bible_id, book["id"])
chapter = random.choice(chapters)
chapters = await self._get_chapters(bible_id, book["id"])
chapter = random.choice(chapters)
verses = await self._get_verses(bible_id, book["id"], chapter["number"])
verse = random.choice(verses)["id"]
verses = await self._get_verses(bible_id, book["id"], chapter["number"])
verse = random.choice(verses)["id"]
passage = await self._get_passage(bible_id, verse, False)
passage = await self._get_passage(bible_id, verse, False)
except (
bible.errors.BibleAccessError,
bible.errors.NotFound,
bible.errors.Unauthorized,
) as e:
await ctx.send(e.message)
return
embed = Embed(
title=f"{passage['reference']}",
@ -197,25 +205,3 @@ class Bible(commands.Cog):
)
embed.set_footer(text=f"{ctx.prefix}bible random - Powered by API.bible")
await ctx.send(embed=embed)
@bible_passage.error
@bible_random.error
async def error_handler(self, ctx: commands.Context, err):
if isinstance(err, bible.errors.Unauthorized):
await ctx.send(
error(
"""The API key for API.bible is missing or invalid. Please report this to the bot owner.
If you are the bot owner, please check the documentation [here](https://seacogs.coastalcommits.com/bible/#setup)."""
)
)
return
elif isinstance(err, bible.errors.BibleAccessError):
await ctx.send(
error(
"The provided API key cannot retrieve sections from the configured Bible. Please report this to the bot owner."
)
)
return
elif isinstance(err, bible.errors.NotFound):
await ctx.send(error("The requested passage was not found."))
return

View file

@ -1,10 +1,33 @@
from redbot.core.utils.chat_formatting import error
class BibleAccessError(Exception):
pass
def __init__(
self,
message: str = error(
"The provided API key cannot retrieve sections from the configured Bible. Please report this to the bot owner."
),
):
super().__init__(message)
self.message = message
class Unauthorized(Exception):
pass
def __init__(
self,
message: str = error(
"""The API key for API.bible is missing or invalid. Please report this to the bot owner.
If you are the bot owner, please check the documentation [here](https://seacogs.coastalcommits.com/bible/#setup)."""
),
):
super().__init__(message)
self.message = message
class NotFound(Exception):
pass
def __init__(
self,
message: str = error("The requested passage was not found."),
):
super().__init__(message)
self.message = message