import discord from discord import app_commands import os import requests import asyncio from threading import Thread # --- 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." ) # --- Discord Bot Setup --- intents = discord.Intents.default() # intents.message_content = True # If you need message content intent in the future client = discord.Client(intents=intents) tree = app_commands.CommandTree(client) # --- GLIF API Interaction --- def generate_image(prompt, aspect_ratio): payload = { "id": "cm3ugmzv2002gnckiosrwk6xi", # Your GLIF model ID "inputs": [prompt, aspect_ratio], } headers = {"Authorization": f"Bearer {GLIF_API_TOKEN}"} response = requests.post(GLIF_API_URL, json=payload, headers=headers) if response.status_code == 200: response_data = response.json() if "output" in response_data: return response_data["output"] elif "error" in response_data: return f"Error: {response_data['error']}" else: return f"API request failed with status code: {response.status_code}" # --- Discord Slash Commands --- @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.""" await interaction.response.defer() try: image_url = generate_image(prompt, aspect_ratio.value) if image_url.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}" ) else: await interaction.followup.send( f"Sorry, I couldn't generate an image. {image_url}" ) except Exception as e: await interaction.followup.send(f"An error occurred: {e}") @tree.command(name="hello", description="Says hello!") async def hello_command(interaction): await interaction.response.send_message("Hello there!") # --- Bot Initialization and Event Loop --- async def on_ready(): await tree.sync() print("Bot is ready!") client.event(on_ready) async def main(): # Start the bot async with client: await client.start(DISCORD_BOT_TOKEN) print("Bot has stopped.") if __name__ == "__main__": asyncio.run(main())