fix(bible): close asyncio session after unloading the cog
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 35s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 40s

This commit is contained in:
cswimr 2025-01-26 00:39:09 +00:00
parent 7d1a9cc01a
commit 2859f93501
Signed by: cswimr
GPG key ID: 0EC431A8DA8F8087
2 changed files with 15 additions and 32 deletions

View file

@ -6,6 +6,7 @@
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
import random
from asyncio import create_task
from io import BytesIO
import aiohttp
@ -26,20 +27,21 @@ class Bible(commands.Cog):
__author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"]
__git__ = "https://www.coastalcommits.com/cswimr/SeaCogs"
__version__ = "1.1.1"
__version__ = "1.1.2"
__documentation__ = "https://seacogs.coastalcommits.com/pterodactyl/"
def __init__(self, bot: Red):
super().__init__()
self.bot = bot
self.session = aiohttp.ClientSession()
self.config = Config.get_conf(
self, identifier=481923957134912, force_registration=True
)
self.config = Config.get_conf(self, identifier=481923957134912, force_registration=True)
self.logger = getLogger("red.SeaCogs.Bible")
self.config.register_global(bible="de4e12af7f28f599-02")
self.config.register_user(bible=None)
def cog_unload(self):
create_task(self.session.close())
def format_help_for_context(self, ctx: commands.Context) -> str:
pre_processed = super().format_help_for_context(ctx) or ""
n = "\n" if "\n\n" not in pre_processed else ""
@ -51,14 +53,13 @@ class Bible(commands.Cog):
]
return "\n".join(text)
def get_icon(self, color: Colour) -> File:
"""Get the docs.api.bible favicon with a given color."""
image_path = data_manager.bundled_data_path(self) / "api.bible-logo.png"
image = Image.open(image_path)
image = image.convert("RGBA")
data = np.array(image)
red, green, blue, alpha = data.T # pylint: disable=unused-variable
red, green, blue, alpha = data.T # pylint: disable=unused-variable
white_areas = (red == 255) & (blue == 255) & (green == 255)
data[..., :-1][white_areas.T] = color.to_rgb()
image = Image.fromarray(data)
@ -70,9 +71,7 @@ class Bible(commands.Cog):
async def translate_book_name(self, bible_id: str, book_name: str) -> str:
"""Translate a book name to a book ID."""
book_name_list = [
w.lower() if w.lower() == "of" else w.title() for w in book_name.split()
]
book_name_list = [w.lower() if w.lower() == "of" else w.title() for w in book_name.split()]
book_name = " ".join(book_name_list)
books = await self._get_books(bible_id)
for book in books:
@ -247,13 +246,9 @@ class Bible(commands.Cog):
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(
ctx, bible_id, f"{book_id}.{from_verse}-{book_id}.{to_verse}", True
)
passage = await self._get_passage(ctx, bible_id, f"{book_id}.{from_verse}-{book_id}.{to_verse}", True)
else:
passage = await self._get_passage(
ctx, bible_id, f"{book_id}.{passage.replace(':', '.')}", False
)
passage = await self._get_passage(ctx, bible_id, f"{book_id}.{passage.replace(':', '.')}", False)
except (
bible.errors.BibleAccessError,
bible.errors.NotFound,
@ -275,10 +270,7 @@ class Bible(commands.Cog):
description=passage["content"].replace("", ""),
color=await ctx.embed_color(),
)
embed.set_footer(
text=f"{ctx.prefix}bible passage - Powered by API.Bible - {version.abbreviationLocal} ({version.languageLocal}, {version.descriptionLocal})",
icon_url="attachment://icon.png"
)
embed.set_footer(text=f"{ctx.prefix}bible passage - Powered by API.Bible - {version.abbreviationLocal} ({version.languageLocal}, {version.descriptionLocal})", icon_url="attachment://icon.png")
await ctx.send(embed=embed, file=icon)
else:
await ctx.send(f"## {passage['reference']}\n{passage['content']}")
@ -317,10 +309,7 @@ class Bible(commands.Cog):
description=passage["content"].replace("", ""),
color=await ctx.embed_color(),
)
embed.set_footer(
text=f"{ctx.prefix}bible random - Powered by API.Bible - {version.abbreviationLocal} ({version.languageLocal}, {version.descriptionLocal})",
icon_url="attachment://icon.png"
)
embed.set_footer(text=f"{ctx.prefix}bible random - Powered by API.Bible - {version.abbreviationLocal} ({version.languageLocal}, {version.descriptionLocal})", icon_url="attachment://icon.png")
await ctx.send(embed=embed, file=icon)
else:
await ctx.send(f"## {passage['reference']}\n{passage['content']}")

View file

@ -4,9 +4,7 @@ from redbot.core.utils.chat_formatting import error
class BibleAccessError(Exception):
def __init__(
self,
message: str = error(
"The provided API key cannot retrieve sections from the configured Bible. Please report this to the bot owner."
),
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
@ -15,9 +13,7 @@ class BibleAccessError(Exception):
class Unauthorized(Exception):
def __init__(
self,
message: str = error(
"The API key for API.Bible is missing or invalid. Please report this to the bot owner.\nIf you are the bot owner, please check the documentation [here](<https://seacogs.coastalcommits.com/bible/#setup>)."
),
message: str = error("The API key for API.Bible is missing or invalid. Please report this to the bot owner.\nIf you are the bot owner, please check the documentation [here](<https://seacogs.coastalcommits.com/bible/#setup>)."),
):
super().__init__(message)
self.message = message
@ -44,9 +40,7 @@ class ServiceUnavailable(Exception):
class InexplicableError(Exception):
def __init__(
self,
message: str = error(
"An inexplicable 'Bad Request' error occurred. This error happens occassionally with the API.Bible service. Please try again. If the error persists, please report this to the bot owner."
),
message: str = error("An inexplicable 'Bad Request' error occurred. This error happens occasionally with the API.Bible service. Please try again. If the error persists, please report this to the bot owner."),
):
super().__init__(message)
self.message = message