1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 19:44:20 +00:00
royalnet/royalpack/commands/cat.py

92 lines
2.8 KiB
Python
Raw Normal View History

import io
2021-04-19 17:39:01 +00:00
import logging
import aiohttp
import royalnet.engineer as engi
2021-04-30 13:22:58 +00:00
import royalpack.bolts as rb
log = logging.getLogger(__name__)
2021-04-30 13:22:58 +00:00
@rb.capture_errors
2021-04-17 02:19:11 +00:00
@engi.TeleportingConversation
2021-04-19 03:26:20 +00:00
async def cat(*, _msg: engi.Message, **__):
"""
2021-04-18 14:29:59 +00:00
Invia un gatto in chat! 🐈
"""
log.debug("Creating a new HTTP session")
async with aiohttp.ClientSession() as session:
log.info("Making a GET request to The Cat API Image Search")
async with session.get("https://api.thecatapi.com/v1/images/search") as response:
log.debug("Ensuring the request was successful")
if response.status >= 400:
log.error(f"The Cat API returned an HTTP error: {response.status}")
2021-04-03 16:43:34 +00:00
await _msg.reply(
text="⚠️ Couldn't request a cat from https://thecatapi.com :("
)
return
log.debug("Reading the JSON received from The Cat API")
try:
result = await response.json()
except aiohttp.ContentTypeError:
log.error(f"Couldn't decode received JSON from The Cat API")
2021-04-03 16:43:34 +00:00
await _msg.reply(
text="⚠️ Couldn't understand what the cat from https://thecatapi.com was saying :("
)
return
# Example result:
# [
# {
# "breeds": [],
# "id": "MjAzMjY3MQ",
# "url": "https://cdn2.thecatapi.com/images/MjAzMjY3MQ.jpg",
# "width": 557,
# "height": 724
# }
# ]
log.debug("Ensuring at least one image was received")
if len(result) == 0:
log.error("Didn't receive any image from The Cat API")
2021-04-03 16:43:34 +00:00
await _msg.reply(
text="⚠️ I couldn't find any cats at https://thecatapi.com :("
)
return
# Select the first image received
selected_cat = result[0]
log.debug(f"Selected {selected_cat!r}")
log.debug("Ensuring an image url is available")
if "url" not in selected_cat:
log.error("Image received from The Cat API did not have any URL")
2021-04-03 16:43:34 +00:00
await _msg.reply(
text="⚠️ I found a cat at https://thecatapi.com, but I couldn't find its image :("
)
return
# Download the cat image
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()
2021-04-03 16:43:34 +00:00
while img_data := await response.content.read(8192):
img.write(img_data)
2021-04-03 16:43:34 +00:00
img.seek(0)
log.debug("Sending image in the chat")
2021-04-03 16:43:34 +00:00
await _msg.reply(files=[img])
# Objects exported by this module
__all__ = (
"cat",
)