""" Provides a command to fetch random xkcd comic """ import requests import tempfile import random import simplematrixbotlib as botlib # Define the XKCD API URL XKCD_API_URL = "https://xkcd.com/info.0.json" async def handle_command(room, message, bot, prefix, config): match = botlib.MessageMatch(room, message, bot, prefix) if match.prefix() and match.command("xkcd"): # Fetch the latest comic number from XKCD API try: response = requests.get(XKCD_API_URL, timeout=10) response.raise_for_status() # Raise an exception for non-200 status codes latest_comic_num = response.json()["num"] # Choose a random comic number random_comic_num = random.randint(1, latest_comic_num) # Fetch the random comic data random_comic_url = f"https://xkcd.com/{random_comic_num}/info.0.json" comic_response = requests.get(random_comic_url, timeout=10) comic_response.raise_for_status() comic_data = comic_response.json() image_url = comic_data["img"] # Download the image image_response = requests.get(image_url, timeout=10) image_response.raise_for_status() # Use secure temporary file with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as temp_file: image_path = temp_file.name temp_file.write(image_response.content) # Send the image to the room await bot.api.send_image_message(room_id=room.room_id, image_filepath=image_path) # Clean up temp file import os os.remove(image_path) except Exception as e: await bot.api.send_text_message(room.room_id, f"Error fetching XKCD comic: {str(e)}")