python-discord / king-arthur

King Arthur is the DevOps helper bot for Python Discord
MIT License
10 stars 7 forks source link

Programming Quote Command #230

Closed jchristgit closed 2 months ago

jchristgit commented 2 months ago

We should add a command to King Arthur that displays a programming quote from http://quotes.cat-v.org/programming/.

For Bella, who has generously agreed to implement this feature, I have already prepared the proposed parser logic below. The Cat-V websites provides a HTML-based API, we simply need to install the BeautifulSoup API wrapper to consume this API.

from bs4 import BeautifulSoup

import urllib.request
from typing import NamedTuple

class Quote(NamedTuple):
    text: str
    source: str | None

with urllib.request.urlopen("http://quotes.cat-v.org/programming/") as request:
    response = request.read()

soup = BeautifulSoup(response, 'html.parser')
prev_text = None
quotes = []
for item in soup.article.find_all('p'):
    text = item.get_text().replace('\xa0', '')
    if prev_text is not None:
        if text.startswith('—'):
            quotes.append(Quote(text=prev_text, source=text.removeprefix("— ")))
        elif not prev_text.startswith("—"):
            quotes.append(Quote(text=prev_text, source=None))

    prev_text = text