Spaces:
Running
Running
import os | |
import discord | |
from discord.ext import commands | |
import requests | |
# Load the bot token and API key from environment variables | |
DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN") | |
GLIF_API_KEY = os.getenv("GLIF_API_KEY") | |
GLIF_API_URL = "https://simple-api.glif.app" | |
# Create a bot instance with the command prefix '!' | |
intents = discord.Intents.default() | |
bot = commands.Bot(command_prefix="/imagine", intents=intents) | |
# Function to call the GLIF API | |
def generate_image(prompt): | |
aspect_ratio = "9:16" # Hardcoded aspect ratio | |
payload = { | |
"id": "cm3ugmzv2002gnckiosrwk6xi", # Your GLIF ID | |
"inputs": [prompt, aspect_ratio] | |
} | |
headers = {"Authorization": f"Bearer {GLIF_API_KEY}"} | |
try: | |
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"] # Image URL | |
elif "error" in response_data: | |
return f"Error: {response_data['error']}" | |
else: | |
return f"API request failed with status code: {response.status_code}" | |
except Exception as e: | |
return f"Error: {str(e)}" | |
# Command to generate an image | |
async def generate(ctx, *, prompt: str): | |
await ctx.send(f"Generating an image for: `{prompt}`...") | |
image_url = generate_image(prompt) | |
if image_url.startswith("http"): | |
await ctx.send(image_url) # Send the image URL | |
else: | |
await ctx.send(f"Failed to generate image: {image_url}") | |
# Event: Bot is ready | |
async def on_ready(): | |
print(f"Logged in as {bot.user}") | |
# Run the bot | |
bot.run(DISCORD_BOT_TOKEN) | |