""" Plugin for fetching jokes from the Official Joke API. """ import logging import aiohttp import simplematrixbotlib as botlib async def handle_command(room, message, bot, prefix, config): match = botlib.MessageMatch(room, message, bot, prefix) if match.is_not_from_this_bot() and match.prefix() and match.command("joke"): args = match.args() category = "general" if args: category = args[0].lower() if category not in ("general", "programming"): category = "general" logging.info(f"Fetching {category} joke") try: if category == "programming": url = "https://official-joke-api.appspot.com/jokes/programming/random" else: url = "https://official-joke-api.appspot.com/random_joke" async with aiohttp.ClientSession() as session: async with session.get(url, timeout=10) as response: if response.status == 200: data = await response.json() if isinstance(data, list) and data: joke = data[0] elif isinstance(data, dict): joke = data else: await bot.api.send_text_message(room.room_id, "Sorry, couldn't fetch a joke.") return setup = joke.get("setup", "No setup") punchline = joke.get("punchline", "No punchline") await bot.api.send_text_message(room.room_id, setup) import asyncio await asyncio.sleep(2) await bot.api.send_text_message(room.room_id, f"... {punchline}") else: await bot.api.send_text_message(room.room_id, "Sorry, couldn't fetch a joke.") except Exception as e: logging.error(f"Error fetching joke: {e}") await bot.api.send_text_message(room.room_id, f"Error fetching joke: {str(e)}") __version__ = "1.0.1" __author__ = "Funguy Bot" __description__ = "Get random jokes from the Official Joke API" __help__ = """
!joke – Random jokes

!joke for general, !joke programming for programming jokes.

"""