From 9e2697b08b2ae7fcf2cca59727d4c5aa45ec9e6f Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 1 Feb 2024 19:10:05 -0500 Subject: [PATCH] fix(bible): added errors and debug logging --- bible/bible.py | 70 ++++++++++++++++++++++++++++++++++++++++++++----- bible/errors.py | 6 +++++ 2 files changed, 70 insertions(+), 6 deletions(-) create mode 100644 bible/errors.py diff --git a/bible/bible.py b/bible/bible.py index 102e5e8..a1d249b 100644 --- a/bible/bible.py +++ b/bible/bible.py @@ -13,6 +13,8 @@ from discord import Embed from redbot.core import Config, commands from redbot.core.bot import Red +from bible.errors import BibleAccessError, Unauthorized + class Bible(commands.Cog): """Retrieve Bible verses from the API.bible API.""" @@ -40,11 +42,32 @@ class Bible(commands.Cog): return book["id"] raise ValueError(f"Book {book_name} not found.") - async def _get_passage(self, bible_id: str, passage_id: str) -> dict: + async def _get_passage( + self, bible_id: str, passage_id: str, include_verse_numbers: bool + ) -> dict: """Get a Bible passage from the API.bible API.""" - url = f"https://api.scripture.api.bible/v1/bibles/{bible_id}/passages/{passage_id}?content-type=text&include-notes=false&include-titles=false&include-chapter-numbers=false&include-verse-numbers=true&include-verse-spans=false&use-org-id=false" + url = f"https://api.scripture.api.bible/v1/bibles/{bible_id}/passages/{passage_id}" headers = await self.bot.get_shared_api_tokens("api.bible") - async with self.session.get(url, headers=headers) as response: + params = { + "content-type": "text", + "include-notes": False, + "include-titles": False, + "include-chapter-numbers": False, + "include-verse-numbers": include_verse_numbers, + "include-verse-spans": False, + "use-org-id": False, + } + + async with self.session.get(url, headers=headers, params=params) as response: + self.logger.debug( + "_get_passage executed with a response code of: %s", response.status + ) + if response.status == 401: + raise Unauthorized("Missing/Invalid API key.") + if response.status == 403: + raise BibleAccessError( + "The provided API key cannot retrieve sections from the configured Bible." + ) data = await response.json() return data["data"] @@ -52,7 +75,17 @@ class Bible(commands.Cog): """Get the books of the Bible from the API.bible API.""" url = f"https://api.scripture.api.bible/v1/bibles/{bible_id}/books" headers = await self.bot.get_shared_api_tokens("api.bible") + async with self.session.get(url, headers=headers) as response: + self.logger.debug( + "_get_books executed with a response code of: %s", response.status + ) + if response.status == 401: + raise Unauthorized("Missing/Invalid API key.") + if response.status == 403: + raise BibleAccessError( + "The provided API key cannot retrieve sections from the configured Bible." + ) data = await response.json() return data["data"] @@ -60,7 +93,17 @@ class Bible(commands.Cog): """Get the chapters of a book from the API.bible API.""" url = f"https://api.scripture.api.bible/v1/bibles/{bible_id}/books/{book_id}/chapters" headers = await self.bot.get_shared_api_tokens("api.bible") + async with self.session.get(url, headers=headers) as response: + self.logger.debug( + "_get_chapters executed with a response code of: %s", response.status + ) + if response.status == 401: + raise Unauthorized("Missing/Invalid API key.") + if response.status == 403: + raise BibleAccessError( + "The provided API key cannot retrieve sections from the configured Bible." + ) data = await response.json() return data["data"] @@ -68,7 +111,17 @@ class Bible(commands.Cog): """Get the verses of a chapter from the API.bible API.""" url = f"https://api.scripture.api.bible/v1/bibles/{bible_id}/chapters/{book_id}.{chapter}/verses" headers = await self.bot.get_shared_api_tokens("api.bible") + async with self.session.get(url, headers=headers) as response: + self.logger.debug( + "_get_verses executed with a response code of: %s", response.status + ) + if response.status == 401: + raise Unauthorized("Missing/Invalid API key.") + if response.status == 403: + raise BibleAccessError( + "The provided API key cannot retrieve sections from the configured Bible." + ) data = await response.json() return data["data"] @@ -96,11 +149,11 @@ class Bible(commands.Cog): 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}" + 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(':', '.')}" + bible_id, f"{book_id}.{passage.replace(':', '.')}", False ) if len(passage["content"]) > 4096: @@ -119,13 +172,18 @@ class Bible(commands.Cog): async def bible_random(self, ctx: commands.Context): """Get a random Bible verse.""" bible_id = await self.config.bible() + books = await self._get_books(bible_id) book = random.choice(books) + 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"] - passage = await self._get_passage(bible_id, verse) + + passage = await self._get_passage(bible_id, verse, False) + embed = Embed( title=f"{passage['reference']}", description=passage["content"].replace("ΒΆ ", ""), diff --git a/bible/errors.py b/bible/errors.py new file mode 100644 index 0000000..0bbb571 --- /dev/null +++ b/bible/errors.py @@ -0,0 +1,6 @@ +class BibleAccessError(Exception): + pass + + +class Unauthorized(Exception): + pass