artintel235 commited on
Commit
6fb9e78
·
verified ·
1 Parent(s): 3f11bbc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -51
app.py CHANGED
@@ -1,95 +1,117 @@
1
  import discord
2
  from discord import app_commands
3
  import os
4
- from dotenv import load_dotenv
5
  import requests
 
6
 
7
- load_dotenv()
 
 
 
 
 
 
 
 
 
8
 
9
- # Set up intents
10
  intents = discord.Intents.default()
 
11
  client = discord.Client(intents=intents)
12
  tree = app_commands.CommandTree(client)
13
 
14
- # GLIF Simple API endpoint
15
- GLIF_API_URL = "https://simple-api.glif.app"
 
 
16
 
 
 
 
17
 
18
- # Function to call the GLIF API
19
- def generate_image(prompt, aspect_ratio):
20
- # Prepare the payload for the GLIF API
21
  payload = {
22
- "id": "cm3ugmzv2002gnckiosrwk6xi", # Glif ID
23
- "inputs": [prompt, aspect_ratio]
24
  }
 
25
 
26
- # Set up headers with the API token
27
- headers = {"Authorization": f"Bearer {os.getenv('GLIF_API_TOKEN')}"}
28
-
29
- # Make the request to the GLIF API
30
- response = requests.post(GLIF_API_URL, json=payload, headers=headers)
31
 
32
- if response.status_code == 200:
33
- # Parse the response
34
  response_data = response.json()
35
  if "output" in response_data:
36
- # Return the image URL
37
  return response_data["output"]
38
  elif "error" in response_data:
39
- # Handle errors (even though the status code is 200)
40
  return f"Error: {response_data['error']}"
41
- else:
42
- return f"API request failed with status code: {response.status_code}"
43
-
44
-
45
- # Define a slash command for image generation
46
- @tree.command(name="generate",
47
- description="Generates an image based on a text prompt")
48
- @app_commands.choices(aspect_ratio=[
49
- app_commands.Choice(name="1:1 (Square)", value="1:1"),
50
- app_commands.Choice(name="9:16 (Vertical)", value="9:16"),
51
- app_commands.Choice(name="16:9 (Horizontal)", value="16:9"),
52
- app_commands.Choice(name="4:5 (Portrait)", value="4:5"),
53
- app_commands.Choice(name="5:4 (Landscape)", value="5:4"),
54
- app_commands.Choice(name="3:4 (Portrait)", value="3:4"),
55
- app_commands.Choice(name="4:3 (Landscape)", value="4:3")
56
- ])
57
- async def generate_command(interaction: discord.Interaction, prompt: str,
58
- aspect_ratio: app_commands.Choice[str]):
 
 
 
 
 
 
 
 
59
  """Generates an image based on the user's prompt and aspect ratio."""
60
  await interaction.response.defer() # Acknowledge the interaction
61
 
62
  try:
63
  image_url = generate_image(prompt, aspect_ratio.value)
64
-
65
  if image_url.startswith("http"):
66
  await interaction.followup.send(
67
  f"Here's your generated image based on the prompt '{prompt}' with aspect ratio {aspect_ratio.name}:\n{image_url}"
68
  )
69
  else:
70
  await interaction.followup.send(
71
- f"Sorry, I couldn't generate an image. {image_url}")
 
72
  except Exception as e:
73
  await interaction.followup.send(f"An error occurred: {e}")
74
 
75
-
76
- # Define the hello slash command
77
  @tree.command(name="hello", description="Says hello!")
78
  async def hello_command(interaction):
79
  await interaction.response.send_message("Hello there!")
80
 
81
-
82
- @client.event
83
  async def on_ready():
84
- await tree.sync() # Sync the slash commands with discord
85
  print("Bot is ready!")
86
 
 
 
 
 
 
 
 
 
87
 
88
- # Get the token from an environment variable
89
- token = os.getenv("DISCORD_BOT_TOKEN")
 
90
 
91
- # check if the token is a string
92
- if isinstance(token, str):
93
- client.run(token)
94
- else:
95
- print("Invalid token format")
 
1
  import discord
2
  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")
9
+ GLIF_API_TOKEN = os.getenv("GLIF_API_TOKEN")
10
+ GLIF_API_URL = "https://simple-api.glif.app"
11
+
12
+ # Check if tokens are set
13
+ if not DISCORD_BOT_TOKEN or not GLIF_API_TOKEN:
14
+ raise ValueError(
15
+ "Both DISCORD_BOT_TOKEN and GLIF_API_TOKEN must be set as environment variables in the Hugging Face Space's settings."
16
+ )
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.
31
+ aspect_ratio: The desired aspect ratio (e.g., "1:1", "16:9").
32
 
33
+ Returns:
34
+ The URL of the generated image, or an error message if the API request failed.
35
+ """
36
  payload = {
37
+ "id": "cm3ugmzv2002gnckiosrwk6xi", # Your GLIF model ID
38
+ "inputs": [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(
59
+ name="generate", description="Generates an image based on a text prompt"
60
+ )
61
+ @app_commands.choices(
62
+ aspect_ratio=[
63
+ app_commands.Choice(name="1:1 (Square)", value="1:1"),
64
+ app_commands.Choice(name="9:16 (Vertical)", value="9:16"),
65
+ app_commands.Choice(name="16:9 (Horizontal)", value="16:9"),
66
+ app_commands.Choice(name="4:5 (Portrait)", value="4:5"),
67
+ app_commands.Choice(name="5:4 (Landscape)", value="5:4"),
68
+ app_commands.Choice(name="3:4 (Portrait)", value="3:4"),
69
+ app_commands.Choice(name="4:3 (Landscape)", value="4:3"),
70
+ ]
71
+ )
72
+ async def generate_command(
73
+ interaction: discord.Interaction,
74
+ prompt: str,
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!")
96
 
97
+ # --- Bot Initialization and Event Loop ---
 
98
  async def on_ready():
99
+ await tree.sync()
100
  print("Bot is ready!")
101
 
102
+ client.event(on_ready)
103
+
104
+ async def main():
105
+ print("Inside main()")
106
+ async with client:
107
+ print("Starting client...")
108
+ await client.start(DISCORD_BOT_TOKEN)
109
+ print("Bot has started.")
110
 
111
+ # Keep the main function alive:
112
+ while True:
113
+ await asyncio.sleep(60) # Sleep for 60 seconds
114
 
115
+ if __name__ == "__main__":
116
+ print("Running main()")
117
+ asyncio.run(main())