Skip to content

Commit

Permalink
Merge pull request #235 from python-discord/quotes
Browse files Browse the repository at this point in the history
Add a quotes command
  • Loading branch information
shtlrs authored Jul 13, 2024
2 parents 91eec09 + 153aa0d commit 535c54b
Show file tree
Hide file tree
Showing 3 changed files with 104 additions and 5 deletions.
67 changes: 67 additions & 0 deletions arthur/exts/fun/quotes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import random
from typing import NamedTuple

import aiohttp
from bs4 import BeautifulSoup
from discord.ext import commands

from arthur import KingArthur
from arthur.log import logger


class Quote(NamedTuple):
"""A data structure to hold quotes and their source."""

text: str
source: str | None

def __str__(self):
return f"{self.text}\n-- {self.source}"


class QuotesCog(commands.Cog):
"""A cog that sends programming quotes."""

def __init__(self, bot: KingArthur) -> None:
self.bot = bot
self.quotes = []

async def cog_load(self) -> None:
"""Fetch the quotes to be used."""
try:
async with self.bot.http_session.get(
"http://quotes.cat-v.org/programming/"
) as response:
content = await response.content.read()
except aiohttp.ClientResponseError:
logger.exception("Couldn't fetch programming quotes.")
return

soup = BeautifulSoup(content, "html.parser")
prev_text = None

for item in soup.article.find_all("p"):
text = item.get_text().replace("\xa0", "")

if prev_text is not None:
if text.startswith("—"):
self.quotes.append(Quote(text=prev_text, source=text.removeprefix("— ")))
elif not prev_text.startswith("—"):
self.quotes.append(Quote(text=prev_text, source=None))

prev_text = text

@commands.command(name="quote")
async def quote(self, ctx: commands.Context) -> None:
"""Send a random programming quote."""
if not self.quotes:
await ctx.reply(":x: Couldn't fetch quotes, try reloading the cog.")
return

quote = random.choice(self.quotes)
await ctx.reply(str(quote))


async def setup(bot: KingArthur) -> None:
"""Load the QuotesCog."""
await bot.add_cog(QuotesCog(bot))
41 changes: 36 additions & 5 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ python = "3.12.*"
# See https://bot-core.pythondiscord.com/ for docs.
pydis-core = "11.2.0"

beautifulsoup4 = "4.12.3"
pydantic = "2.8.2"
pydantic-settings = "2.3.4"
loguru = "0.7.2"
Expand Down

0 comments on commit 535c54b

Please sign in to comment.