|
| 1 | +import asyncio |
| 2 | +import io |
| 3 | +from urllib.parse import quote_plus |
| 4 | + |
| 5 | +import aiohttp |
| 6 | +import discord |
| 7 | +from discord import app_commands |
| 8 | +from discord.ext import commands |
| 9 | +from loguru import logger |
| 10 | +from PIL import Image |
| 11 | + |
| 12 | +from tux.bot import Tux |
| 13 | +from tux.ui.embeds import EmbedCreator |
| 14 | +from tux.utils.config import CONFIG |
| 15 | + |
| 16 | + |
| 17 | +class Wolfram(commands.Cog): |
| 18 | + def __init__(self, bot: Tux) -> None: |
| 19 | + self.bot = bot |
| 20 | + |
| 21 | + # Verify AppID configuration; unload cog if missing |
| 22 | + if not CONFIG.WOLFRAM_APP_ID: |
| 23 | + logger.warning("Wolfram Alpha API ID is not set. Some Science/Math commands will not work.") |
| 24 | + # Store the task reference |
| 25 | + self._unload_task = asyncio.create_task(self._unload_self()) |
| 26 | + else: |
| 27 | + logger.info("Wolfram Alpha API ID is set, Science/Math commands that depend on it will work.") |
| 28 | + |
| 29 | + async def _unload_self(self): |
| 30 | + """Unload this cog if configuration is missing.""" |
| 31 | + try: |
| 32 | + await self.bot.unload_extension("tux.cogs.tools.wolfram") |
| 33 | + logger.info("Wolfram cog has been unloaded due to missing configuration") |
| 34 | + except Exception as e: |
| 35 | + logger.error(f"Failed to unload Wolfram cog: {e}") |
| 36 | + |
| 37 | + @commands.hybrid_command(name="wolfram", description="Query Wolfram|Alpha Simple API and return an image result.") |
| 38 | + @app_commands.describe( |
| 39 | + query="The input query for Wolfram|Alpha, e.g. 'integrate x^2' or 'What is the capital of France?'", |
| 40 | + ) |
| 41 | + async def wolfram(self, ctx: commands.Context[Tux], *, query: str) -> None: |
| 42 | + """ |
| 43 | + Send a query to Wolfram|Alpha Simple API and return the visual result. |
| 44 | +
|
| 45 | + Parameters |
| 46 | + ---------- |
| 47 | + ctx : commands.Context[Tux] |
| 48 | + Invocation context for the command. |
| 49 | + query : str |
| 50 | + Input string for the Wolfram|Alpha query, e.g. 'integrate x^2'. |
| 51 | + """ |
| 52 | + |
| 53 | + await ctx.defer() |
| 54 | + |
| 55 | + # Build the Simple API endpoint URL with URL-encoded query |
| 56 | + encoded = quote_plus(query) |
| 57 | + url = f"https://api.wolframalpha.com/v1/simple?appid={CONFIG.WOLFRAM_APP_ID}&i={encoded}" |
| 58 | + |
| 59 | + try: |
| 60 | + # Perform async HTTP GET with a 10-second timeout |
| 61 | + timeout = aiohttp.ClientTimeout(total=10) |
| 62 | + async with aiohttp.ClientSession() as session, session.get(url, timeout=timeout) as resp: |
| 63 | + resp.raise_for_status() |
| 64 | + img_data = await resp.read() |
| 65 | + except Exception: |
| 66 | + # On error, notify user via an error embed |
| 67 | + embed = EmbedCreator.create_embed( |
| 68 | + bot=self.bot, |
| 69 | + embed_type=EmbedCreator.ERROR, |
| 70 | + user_name=ctx.author.name, |
| 71 | + user_display_avatar=ctx.author.display_avatar.url, |
| 72 | + description="Failed to retrieve image from Wolfram|Alpha Simple API.", |
| 73 | + ) |
| 74 | + await ctx.send(embed=embed) |
| 75 | + return |
| 76 | + |
| 77 | + # Crop the top 80 pixels from the fetched image |
| 78 | + image = Image.open(io.BytesIO(img_data)) |
| 79 | + width, height = image.size |
| 80 | + cropped = image.crop((0, 80, width, height)) |
| 81 | + buffer = io.BytesIO() |
| 82 | + cropped.save(buffer, format=image.format or "PNG") |
| 83 | + buffer.seek(0) |
| 84 | + image_file = discord.File(buffer, filename="wolfram.png") |
| 85 | + |
| 86 | + embed = EmbedCreator.create_embed( |
| 87 | + bot=self.bot, |
| 88 | + embed_type=EmbedCreator.INFO, |
| 89 | + user_name=ctx.author.name, |
| 90 | + user_display_avatar=ctx.author.display_avatar.url, |
| 91 | + title=f"Wolfram|Alpha: {query}", |
| 92 | + ) |
| 93 | + # Display the image via embed attachment URL |
| 94 | + embed.set_image(url="attachment://wolfram.png") |
| 95 | + await ctx.send(embed=embed, file=image_file) |
| 96 | + |
| 97 | + |
| 98 | +async def setup(bot: Tux) -> None: |
| 99 | + await bot.add_cog(Wolfram(bot)) |
0 commit comments