artintel235 commited on
Commit
4f29568
·
verified ·
1 Parent(s): c1264f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -33
app.py CHANGED
@@ -3,6 +3,7 @@ from discord import app_commands
3
  import os
4
  import requests
5
  import asyncio
 
6
 
7
  # --- Environment Variables & Setup ---
8
  DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
@@ -17,14 +18,14 @@ if not DISCORD_BOT_TOKEN or not GLIF_API_TOKEN:
17
 
18
  # --- Discord Bot Setup ---
19
  intents = discord.Intents.default()
20
- # intents.message_content = True # Uncomment if you need message content intent
21
  client = discord.Client(intents=intents)
22
  tree = app_commands.CommandTree(client)
23
 
24
- # --- GLIF API Interaction ---
25
- def generate_image(prompt, aspect_ratio):
26
  """
27
- Generates an image using the GLIF API based on the given prompt and aspect ratio.
28
 
29
  Args:
30
  prompt: The text prompt for image generation.
@@ -39,20 +40,25 @@ def generate_image(prompt, aspect_ratio):
39
  }
40
  headers = {"Authorization": f"Bearer {GLIF_API_TOKEN}"}
41
 
42
- try:
43
- response = requests.post(GLIF_API_URL, json=payload, headers=headers)
44
- response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
45
-
46
- response_data = response.json()
47
- if "output" in response_data:
48
- return response_data["output"]
49
- elif "error" in response_data:
50
- return f"Error: {response_data['error']}"
51
- else:
52
- return "Error: Unexpected response from GLIF API."
53
-
54
- except requests.exceptions.RequestException as e:
55
- return f"API request failed: {e}"
 
 
 
 
 
56
 
57
  # --- Discord Slash Commands ---
58
  @tree.command(
@@ -75,24 +81,25 @@ async def generate_command(
75
  aspect_ratio: app_commands.Choice[str],
76
  ):
77
  """Generates an image based on the user's prompt and aspect ratio."""
78
- await interaction.response.defer() # Acknowledge the interaction
79
-
80
- try:
81
- image_url = generate_image(prompt, aspect_ratio.value)
82
- if image_url.startswith("http"):
83
- await interaction.followup.send(
84
- f"Here's your generated image based on the prompt '{prompt}' with aspect ratio {aspect_ratio.name}:\n{image_url}"
85
- )
86
- else:
87
- await interaction.followup.send(
88
- f"Sorry, I couldn't generate an image. {image_url}"
89
- )
90
- except Exception as e:
91
- await interaction.followup.send(f"An error occurred: {e}")
 
92
 
93
  @tree.command(name="hello", description="Says hello!")
94
  async def hello_command(interaction):
95
- await interaction.response.send_message("Hello there!I think I got this!")
96
 
97
  # --- Bot Initialization and Event Loop ---
98
  async def on_ready():
 
3
  import os
4
  import requests
5
  import asyncio
6
+ import aiohttp # Use aiohttp for asynchronous HTTP requests
7
 
8
  # --- Environment Variables & Setup ---
9
  DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
 
18
 
19
  # --- Discord Bot Setup ---
20
  intents = discord.Intents.default()
21
+ # intents.message_content = True # If you need message content intent
22
  client = discord.Client(intents=intents)
23
  tree = app_commands.CommandTree(client)
24
 
25
+ # --- Asynchronous GLIF API Interaction with aiohttp ---
26
+ async def generate_image_async(prompt, aspect_ratio):
27
  """
28
+ Generates an image using the GLIF API asynchronously.
29
 
30
  Args:
31
  prompt: The text prompt for image generation.
 
40
  }
41
  headers = {"Authorization": f"Bearer {GLIF_API_TOKEN}"}
42
 
43
+ async with aiohttp.ClientSession() as session:
44
+ try:
45
+ async with session.post(
46
+ GLIF_API_URL, json=payload, headers=headers, timeout=15
47
+ ) as response: # Increased timeout to 15 seconds
48
+ response.raise_for_status()
49
+
50
+ response_data = await response.json()
51
+ if "output" in response_data:
52
+ return response_data["output"]
53
+ elif "error" in response_data:
54
+ return f"Error: {response_data['error']}"
55
+ else:
56
+ return "Error: Unexpected response from GLIF API."
57
+
58
+ except asyncio.TimeoutError:
59
+ return "Error: GLIF API request timed out."
60
+ except aiohttp.ClientError as e:
61
+ return f"API request failed: {e}"
62
 
63
  # --- Discord Slash Commands ---
64
  @tree.command(
 
81
  aspect_ratio: app_commands.Choice[str],
82
  ):
83
  """Generates an image based on the user's prompt and aspect ratio."""
84
+ await interaction.response.defer() # Acknowledge within 3 seconds
85
+
86
+ # Call the asynchronous image generation function
87
+ image_url_or_error = await generate_image_async(
88
+ prompt, aspect_ratio.value
89
+ )
90
+
91
+ if image_url_or_error.startswith("http"):
92
+ await interaction.followup.send(
93
+ f"Here's your generated image based on the prompt '{prompt}' with aspect ratio {aspect_ratio.name}:\n{image_url_or_error}"
94
+ )
95
+ else:
96
+ await interaction.followup.send(
97
+ f"Sorry, I couldn't generate an image. {image_url_or_error}"
98
+ )
99
 
100
  @tree.command(name="hello", description="Says hello!")
101
  async def hello_command(interaction):
102
+ await interaction.response.send_message("Hello there!")
103
 
104
  # --- Bot Initialization and Event Loop ---
105
  async def on_ready():