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 import random
from asyncio import create_task
from io import BytesIO from io import BytesIO
import aiohttp import aiohttp
@ -26,20 +27,21 @@ class Bible(commands.Cog):
__author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"] __author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"]
__git__ = "https://www.coastalcommits.com/cswimr/SeaCogs" __git__ = "https://www.coastalcommits.com/cswimr/SeaCogs"
__version__ = "1.1.1" __version__ = "1.1.2"
__documentation__ = "https://seacogs.coastalcommits.com/pterodactyl/" __documentation__ = "https://seacogs.coastalcommits.com/pterodactyl/"
def __init__(self, bot: Red): def __init__(self, bot: Red):
super().__init__() super().__init__()
self.bot = bot self.bot = bot
self.session = aiohttp.ClientSession() self.session = aiohttp.ClientSession()
self.config = Config.get_conf( self.config = Config.get_conf(self, identifier=481923957134912, force_registration=True)
self, identifier=481923957134912, force_registration=True
)
self.logger = getLogger("red.SeaCogs.Bible") self.logger = getLogger("red.SeaCogs.Bible")
self.config.register_global(bible="de4e12af7f28f599-02") self.config.register_global(bible="de4e12af7f28f599-02")
self.config.register_user(bible=None) 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: def format_help_for_context(self, ctx: commands.Context) -> str:
pre_processed = super().format_help_for_context(ctx) or "" pre_processed = super().format_help_for_context(ctx) or ""
n = "\n" if "\n\n" not in pre_processed else "" n = "\n" if "\n\n" not in pre_processed else ""
@ -51,7 +53,6 @@ class Bible(commands.Cog):
] ]
return "\n".join(text) return "\n".join(text)
def get_icon(self, color: Colour) -> File: def get_icon(self, color: Colour) -> File:
"""Get the docs.api.bible favicon with a given color.""" """Get the docs.api.bible favicon with a given color."""
image_path = data_manager.bundled_data_path(self) / "api.bible-logo.png" image_path = data_manager.bundled_data_path(self) / "api.bible-logo.png"
@ -70,9 +71,7 @@ class Bible(commands.Cog):
async def translate_book_name(self, bible_id: str, book_name: str) -> str: async def translate_book_name(self, bible_id: str, book_name: str) -> str:
"""Translate a book name to a book ID.""" """Translate a book name to a book ID."""
book_name_list = [ book_name_list = [w.lower() if w.lower() == "of" else w.title() for w in book_name.split()]
w.lower() if w.lower() == "of" else w.title() for w in book_name.split()
]
book_name = " ".join(book_name_list) book_name = " ".join(book_name_list)
books = await self._get_books(bible_id) books = await self._get_books(bible_id)
for book in books: for book in books:
@ -247,13 +246,9 @@ class Bible(commands.Cog):
from_verse, to_verse = passage.replace(":", ".").split("-") from_verse, to_verse = passage.replace(":", ".").split("-")
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(ctx, bible_id, f"{book_id}.{from_verse}-{book_id}.{to_verse}", True)
ctx, bible_id, f"{book_id}.{from_verse}-{book_id}.{to_verse}", True
)
else: else:
passage = await self._get_passage( passage = await self._get_passage(ctx, bible_id, f"{book_id}.{passage.replace(':', '.')}", False)
ctx, bible_id, f"{book_id}.{passage.replace(':', '.')}", False
)
except ( except (
bible.errors.BibleAccessError, bible.errors.BibleAccessError,
bible.errors.NotFound, bible.errors.NotFound,
@ -275,10 +270,7 @@ class Bible(commands.Cog):
description=passage["content"].replace("", ""), description=passage["content"].replace("", ""),
color=await ctx.embed_color(), color=await ctx.embed_color(),
) )
embed.set_footer( embed.set_footer(text=f"{ctx.prefix}bible passage - Powered by API.Bible - {version.abbreviationLocal} ({version.languageLocal}, {version.descriptionLocal})", icon_url="attachment://icon.png")
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) await ctx.send(embed=embed, file=icon)
else: else:
await ctx.send(f"## {passage['reference']}\n{passage['content']}") await ctx.send(f"## {passage['reference']}\n{passage['content']}")
@ -317,10 +309,7 @@ class Bible(commands.Cog):
description=passage["content"].replace("", ""), description=passage["content"].replace("", ""),
color=await ctx.embed_color(), color=await ctx.embed_color(),
) )
embed.set_footer( embed.set_footer(text=f"{ctx.prefix}bible random - Powered by API.Bible - {version.abbreviationLocal} ({version.languageLocal}, {version.descriptionLocal})", icon_url="attachment://icon.png")
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) await ctx.send(embed=embed, file=icon)
else: else:
await ctx.send(f"## {passage['reference']}\n{passage['content']}") 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): class BibleAccessError(Exception):
def __init__( def __init__(
self, self,
message: str = error( message: str = error("The provided API key cannot retrieve sections from the configured Bible. Please report this to the bot owner."),
"The provided API key cannot retrieve sections from the configured Bible. Please report this to the bot owner."
),
): ):
super().__init__(message) super().__init__(message)
self.message = message self.message = message
@ -15,9 +13,7 @@ class BibleAccessError(Exception):
class Unauthorized(Exception): class Unauthorized(Exception):
def __init__( def __init__(
self, self,
message: str = error( 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>)."),
"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) super().__init__(message)
self.message = message self.message = message
@ -44,9 +40,7 @@ class ServiceUnavailable(Exception):
class InexplicableError(Exception): class InexplicableError(Exception):
def __init__( def __init__(
self, self,
message: str = error( 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."),
"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."
),
): ):
super().__init__(message) super().__init__(message)
self.message = message self.message = message