1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-22 19:14:20 +00:00

Fix /cat and /dog. Probably

This commit is contained in:
Steffo 2023-12-17 05:15:19 +01:00
parent a408683b46
commit e0e6a334f1
Signed by: steffo
GPG key ID: 2A24051445686895
2 changed files with 41 additions and 11 deletions

View file

@ -1,10 +1,11 @@
import io
import logging
import pathlib
import aiohttp
import royalnet.engineer as engi
import royalpack.bolts as rb
import royalpack.config as cfg
log = logging.getLogger(__name__)
@ -15,6 +16,8 @@ async def cat(*, _msg: engi.Message, **__):
"""
Invia un gatto in chat! 🐈
"""
log.debug("Evaluating config...")
config = cfg.lazy_config.evaluate()
log.debug("Creating a new HTTP session")
async with aiohttp.ClientSession() as session:
@ -75,14 +78,21 @@ async def cat(*, _msg: engi.Message, **__):
log.info("Making a GET request to retrieve a The Cat API image")
async with session.get(selected_cat["url"]) as response:
log.debug("Reading image bytes into memory")
img = io.BytesIO()
while img_data := await response.content.read(8192):
img.write(img_data)
img.seek(0)
filename = selected_cat["url"].split("/")[-1]
path = pathlib.Path(config["files.cache.cat"]).joinpath(filename)
log.debug("Saving cat to: %s", path)
log.debug("Sending image in the chat")
await _msg.reply(files=[img])
with path.open("wb") as img:
log.debug("Reading image bytes into memory")
while img_data := await response.content.read(8192):
img.write(img_data)
img.seek(0)
log.debug("Sending image in the chat")
await _msg.reply(files=[img])
log.debug("Deleting cat...")
path.unlink()
# Objects exported by this module

View file

@ -1,9 +1,14 @@
import logging
import io
import pathlib
import aiohttp
import royalnet.engineer as engi
import royalpack.bolts as rb
import royalpack.config as cfg
log = logging.getLogger(__name__)
@rb.capture_errors
@ -12,13 +17,28 @@ async def dog_any(*, _msg: engi.Message, **__):
"""
Invia un doggo in chat! 🐶
"""
log.debug("Evaluating config...")
config = cfg.lazy_config.evaluate()
async with aiohttp.ClientSession() as session:
log.debug("Fetching dog (not the opposite. ironic, huh?)")
async with session.get("https://dog.ceo/api/breeds/image/random") as response:
result = await response.json()
url = result["message"]
async with session.get(url) as response:
img = await response.content.read()
await _msg.reply(files=[io.BytesIO(img)])
filename = url.split("/")[-1]
path = pathlib.Path(config["files.cache.dog"]).joinpath(filename)
log.debug("Saving dog to: %s", path)
async with session.get(url) as response:
with path.open("wb") as img:
img.write(await response.content.read())
await _msg.reply(files=[img])
path.unlink()
_breeds = [