import discord from discord import app_commands import os import requests import asyncio import aiohttp # Use aiohttp for asynchronous HTTP requests # --- Environment Variables & Setup --- DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN") GLIF_API_TOKEN = os.getenv("GLIF_API_TOKEN") GLIF_API_URL = "https://simple-api.glif.app" # Check if tokens are set if not DISCORD_BOT_TOKEN or not GLIF_API_TOKEN: raise ValueError( "Both DISCORD_BOT_TOKEN and GLIF_API_TOKEN must be set as environment variables in the Hugging Face Space's settings." ) # --- Discord Bot Setup --- intents = discord.Intents.default() # intents.message_content = True # If you need message content intent client = discord.Client(intents=intents) tree = app_commands.CommandTree(client) # --- Asynchronous GLIF API Interaction with aiohttp --- async def generate_image_async(prompt, aspect_ratio): """ Generates an image using the GLIF API asynchronously. Args: prompt: The text prompt for image generation. aspect_ratio: The desired aspect ratio (e.g., "1:1", "16:9"). Returns: The URL of the generated image, or an error message if the API request failed. """ payload = { "id": "cm3ugmzv2002gnckiosrwk6xi", # Your GLIF model ID "inputs": [prompt, aspect_ratio], } headers = {"Authorization": f"Bearer {GLIF_API_TOKEN}"} async with aiohttp.ClientSession() as session: try: async with session.post( GLIF_API_URL, json=payload, headers=headers, timeout=15 ) as response: # Increased timeout to 15 seconds response.raise_for_status() response_data = await response.json() if "output" in response_data: return response_data["output"] elif "error" in response_data: return f"Error: {response_data['error']}" else: return "Error: Unexpected response from GLIF API." except asyncio.TimeoutError: return "Error: GLIF API request timed out." except aiohttp.ClientError as e: return f"API request failed: {e}" @tree.command( name="generate", description="Generates an image based on a text prompt" ) @app_commands.choices( aspect_ratio=[ app_commands.Choice(name="1:1 (Square)", value="1:1"), app_commands.Choice(name="9:16 (Vertical)", value="9:16"), app_commands.Choice(name="16:9 (Horizontal)", value="16:9"), app_commands.Choice(name="4:5 (Portrait)", value="4:5"), app_commands.Choice(name="5:4 (Landscape)", value="5:4"), app_commands.Choice(name="3:4 (Portrait)", value="3:4"), app_commands.Choice(name="4:3 (Landscape)", value="4:3"), ] ) async def generate_command( interaction: discord.Interaction, prompt: str, aspect_ratio: app_commands.Choice[str], ): """Generates an image based on the user's prompt and aspect ratio.""" print(f"Received /generate command from {interaction.user.name}") # Debug print try: await interaction.response.defer(ephemeral=False) # Added ephemeral=False, visible to everyone print("Interaction deferred") # Debug print image_url_or_error = await generate_image_async( prompt, aspect_ratio.value ) print(f"GLIF API response: {image_url_or_error}") # Debug print if image_url_or_error.startswith("http"): await interaction.followup.send( f"Here's your generated image based on the prompt '{prompt}' with aspect ratio {aspect_ratio.name}:\n{image_url_or_error}" ) else: await interaction.followup.send( f"Sorry, I couldn't generate an image. {image_url_or_error}" ) print("Followup sent") # Debug print except Exception as e: print(f"An error occurred: {e}") # More specific error await interaction.followup.send("An error occurred while processing your request.") @tree.command(name="hello", description="Says hello!") async def hello_command(interaction): await interaction.response.send_message("Hello there!") @tree.command(name="testgen", description="Test command") async def testgen_command(interaction: discord.Interaction): print("TestGen command received") await interaction.response.defer() print("TestGen deferred") await interaction.followup.send("TestGen working") # --- Bot Initialization and Event Loop --- async def on_ready(): await tree.sync() print("Bot is ready!") print(f"Guilds: {client.guilds}") client.event(on_ready) async def main(): print("Inside main()") async with client: print("Starting client...") await client.start(DISCORD_BOT_TOKEN) print("Bot has started.") # Keep the main function alive: while True: await asyncio.sleep(60) # Sleep for 60 seconds if __name__ == "__main__": print("Running main()") asyncio.run(main())