feat(bible): added bible random (and formatted with black)
Some checks failed
Actions / Lint Code (Pylint) (push) Failing after 16s
Actions / Build Documentation (MkDocs) (push) Successful in 12s

This commit is contained in:
Seaswimmer 2024-02-01 18:39:10 -05:00
parent b9fba23415
commit 2f945af866
Signed by: cswimr
GPG key ID: B8953EC01E5C4063

View file

@ -5,14 +5,16 @@
# ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ | # ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ |
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_| # |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
import aiohttp
import json import json
import logging import logging
import random
import aiohttp
from discord import Embed from discord import Embed
from redbot.core import commands, Config from redbot.core import Config, commands
from redbot.core.bot import Red from redbot.core.bot import Red
class Bible(commands.Cog): class Bible(commands.Cog):
"""Retrieve Bible verses from the API.bible API.""" """Retrieve Bible verses from the API.bible API."""
@ -23,7 +25,9 @@ class Bible(commands.Cog):
super().__init__() super().__init__()
self.bot = bot self.bot = bot
self.session = aiohttp.ClientSession() 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 = logging.getLogger("red.sea.bible") self.logger = logging.getLogger("red.sea.bible")
self.config.register_global(bible="de4e12af7f28f599-01") self.config.register_global(bible="de4e12af7f28f599-01")
self.config.register_user(bible=None) self.config.register_user(bible=None)
@ -33,8 +37,8 @@ class Bible(commands.Cog):
book_name = book_name.title() book_name = book_name.title()
books = await self._get_books(bible_id) books = await self._get_books(bible_id)
for book in books: for book in books:
if book_name == book['abbreviation'] or book_name == book['name']: if book_name == book["abbreviation"] or book_name == book["name"]:
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) -> dict:
@ -55,12 +59,30 @@ class Bible(commands.Cog):
data = await response.json() data = await response.json()
return data["data"] return data["data"]
async def _get_chapters(self, bible_id: str, book_id: str) -> dict:
"""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:
data = await response.json()
return data["data"]
async def _get_verses(self, bible_id: str, book_id: str, chapter: int) -> dict:
"""Get the verses of a chapter from the API.bible API."""
url = f"https://api.scripture.api.bible/v1/bibles/{bible_id}/books/{book_id}/chapters/{chapter}/verses"
headers = await self.bot.get_shared_api_tokens("api.bible")
async with self.session.get(url, headers=headers) as response:
data = await response.json()
return data["data"]
@commands.group(autohelp=True) @commands.group(autohelp=True)
async def bible(self, ctx: commands.Context): async def bible(self, ctx: commands.Context):
"""Core command for the Bible cog.""" """Core command for the Bible cog."""
@bible.command(name="verse") @bible.command(name="verse")
async def bible_verse(self, ctx: commands.Context, book: str, chapter: int, verse: int) -> str: async def bible_verse(
self, ctx: commands.Context, book: str, chapter: int, verse: int
) -> str:
"""Get a Bible verse.""" """Get a Bible verse."""
bible_id = await self.config.bible() bible_id = await self.config.bible()
try: try:
@ -69,7 +91,11 @@ class Bible(commands.Cog):
await ctx.send(str(e)) await ctx.send(str(e))
return return
passage = await self._get_passage(bible_id, f"{book_id}.{chapter}.{verse}") passage = await self._get_passage(bible_id, f"{book_id}.{chapter}.{verse}")
embed = Embed(title=f"{passage['reference']}", description=passage["content"].replace('', ''), color=await self.bot.get_embed_color(ctx.channel)) embed = Embed(
title=f"{passage['reference']}",
description=passage["content"].replace("", ""),
color=await self.bot.get_embed_color(ctx.channel),
)
embed.set_footer(text=f"{ctx.prefix}bible verse - Powered by API.bible") embed.set_footer(text=f"{ctx.prefix}bible verse - Powered by API.bible")
await ctx.send(embed=embed) await ctx.send(embed=embed)
@ -87,18 +113,47 @@ class Bible(commands.Cog):
await ctx.send(str(e)) await ctx.send(str(e))
return return
if len(passage.split('-')) == 2: if len(passage.split("-")) == 2:
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(bible_id, f"{book_id}.{from_verse}-{book_id}.{to_verse}") passage = await self._get_passage(
bible_id, f"{book_id}.{from_verse}-{book_id}.{to_verse}"
)
else: else:
passage = await self._get_passage(bible_id, f"{book_id}.{passage.replace(':', '.')}") passage = await self._get_passage(
bible_id, f"{book_id}.{passage.replace(':', '.')}"
)
if len(passage["content"]) > 4096: if len(passage["content"]) > 4096:
await ctx.send("The passage is too long to send.") await ctx.send("The passage is too long to send.")
return return
embed = Embed(title=f"{passage['reference']}", description=passage["content"].replace('', ''), color=await self.bot.get_embed_color(ctx.channel)) embed = Embed(
title=f"{passage['reference']}",
description=passage["content"].replace("", ""),
color=await self.bot.get_embed_color(ctx.channel),
)
embed.set_footer(text=f"{ctx.prefix}bible passage - Powered by API.bible") embed.set_footer(text=f"{ctx.prefix}bible passage - Powered by API.bible")
await ctx.send(embed=embed) await ctx.send(embed=embed)
@bible.command(name="random")
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)
passage = await self._get_passage(
bible_id, f"{book['id']}.{chapter['number']}.{verse['number']}"
)
embed = Embed(
title=f"{passage['reference']}",
description=passage["content"].replace("", ""),
color=await self.bot.get_embed_color(ctx.channel),
)
embed.set_footer(text=f"{ctx.prefix}bible random - Powered by API.bible")
await ctx.send(embed=embed)