fix(bible): added errors and debug logging
All checks were successful
Actions / Lint Code (Pylint) (push) Successful in 16s
Actions / Build Documentation (MkDocs) (push) Successful in 12s

This commit is contained in:
Seaswimmer 2024-02-01 19:10:05 -05:00
parent 005d0c1c8b
commit 9e2697b08b
Signed by: cswimr
GPG key ID: B8953EC01E5C4063
2 changed files with 70 additions and 6 deletions

View file

@ -13,6 +13,8 @@ from discord import Embed
from redbot.core import Config, commands from redbot.core import Config, commands
from redbot.core.bot import Red from redbot.core.bot import Red
from bible.errors import BibleAccessError, Unauthorized
class Bible(commands.Cog): class Bible(commands.Cog):
"""Retrieve Bible verses from the API.bible API.""" """Retrieve Bible verses from the API.bible API."""
@ -40,11 +42,32 @@ class Bible(commands.Cog):
return book["id"] return book["id"]
raise ValueError(f"Book {book_name} not found.") 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.""" """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") 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() data = await response.json()
return data["data"] return data["data"]
@ -52,7 +75,17 @@ class Bible(commands.Cog):
"""Get the books of the Bible from the API.bible API.""" """Get the books of the Bible from the API.bible API."""
url = f"https://api.scripture.api.bible/v1/bibles/{bible_id}/books" url = f"https://api.scripture.api.bible/v1/bibles/{bible_id}/books"
headers = await self.bot.get_shared_api_tokens("api.bible") headers = await self.bot.get_shared_api_tokens("api.bible")
async with self.session.get(url, headers=headers) as response: 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() data = await response.json()
return data["data"] return data["data"]
@ -60,7 +93,17 @@ class Bible(commands.Cog):
"""Get the chapters of a book from the API.bible API.""" """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" 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") headers = await self.bot.get_shared_api_tokens("api.bible")
async with self.session.get(url, headers=headers) as response: 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() data = await response.json()
return data["data"] return data["data"]
@ -68,7 +111,17 @@ class Bible(commands.Cog):
"""Get the verses of a chapter from the API.bible API.""" """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" 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") headers = await self.bot.get_shared_api_tokens("api.bible")
async with self.session.get(url, headers=headers) as response: 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() data = await response.json()
return data["data"] return data["data"]
@ -96,11 +149,11 @@ class Bible(commands.Cog):
if "." not in to_verse: if "." not in to_verse:
to_verse = f"{from_verse.split('.')[0]}.{to_verse}" to_verse = f"{from_verse.split('.')[0]}.{to_verse}"
passage = await self._get_passage( 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: else:
passage = await self._get_passage( 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: if len(passage["content"]) > 4096:
@ -119,13 +172,18 @@ class Bible(commands.Cog):
async def bible_random(self, ctx: commands.Context): async def bible_random(self, ctx: commands.Context):
"""Get a random Bible verse.""" """Get a random Bible verse."""
bible_id = await self.config.bible() bible_id = await self.config.bible()
books = await self._get_books(bible_id) books = await self._get_books(bible_id)
book = random.choice(books) book = random.choice(books)
chapters = await self._get_chapters(bible_id, book["id"]) chapters = await self._get_chapters(bible_id, book["id"])
chapter = random.choice(chapters) chapter = random.choice(chapters)
verses = await self._get_verses(bible_id, book["id"], chapter["number"]) verses = await self._get_verses(bible_id, book["id"], chapter["number"])
verse = random.choice(verses)["id"] verse = random.choice(verses)["id"]
passage = await self._get_passage(bible_id, verse)
passage = await self._get_passage(bible_id, verse, False)
embed = Embed( embed = Embed(
title=f"{passage['reference']}", title=f"{passage['reference']}",
description=passage["content"].replace("", ""), description=passage["content"].replace("", ""),

6
bible/errors.py Normal file
View file

@ -0,0 +1,6 @@
class BibleAccessError(Exception):
pass
class Unauthorized(Exception):
pass