artintel235 commited on
Commit
c139e5d
·
verified ·
1 Parent(s): ce17e7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -47
app.py CHANGED
@@ -1,95 +1,105 @@
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
+ from threading import Thread
7
 
8
+ # NOTE: This example requires the "intents" extra to be installed.
9
+ # By default, discord.py does not install it.
10
+ # To install it, run the following command in your terminal:
11
+ # python -m pip install -U discord.py[intents]
12
 
13
+ # --- Environment Variables & Setup ---
14
+ DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
15
+ GLIF_API_TOKEN = os.getenv("GLIF_API_TOKEN")
16
+ GLIF_API_URL = "https://simple-api.glif.app"
17
+
18
+ # Check if tokens are set
19
+ if not DISCORD_BOT_TOKEN or not GLIF_API_TOKEN:
20
+ raise ValueError(
21
+ "Both DISCORD_BOT_TOKEN and GLIF_API_TOKEN must be set as environment variables."
22
+ )
23
+
24
+ # --- Discord Bot Setup ---
25
  intents = discord.Intents.default()
26
+ # intents.message_content = True # If you need message content intent in the future
27
  client = discord.Client(intents=intents)
28
  tree = app_commands.CommandTree(client)
29
 
30
+ # --- GLIF API Interaction ---
 
 
 
 
31
  def generate_image(prompt, aspect_ratio):
 
32
  payload = {
33
+ "id": "cm3ugmzv2002gnckiosrwk6xi", # Your GLIF model ID
34
+ "inputs": [prompt, aspect_ratio],
35
  }
36
+ headers = {"Authorization": f"Bearer {GLIF_API_TOKEN}"}
37
 
 
 
 
 
38
  response = requests.post(GLIF_API_URL, json=payload, headers=headers)
39
 
40
  if response.status_code == 200:
 
41
  response_data = response.json()
42
  if "output" in response_data:
 
43
  return response_data["output"]
44
  elif "error" in response_data:
 
45
  return f"Error: {response_data['error']}"
46
  else:
47
  return f"API request failed with status code: {response.status_code}"
48
 
49
+ # --- Discord Slash Commands ---
50
+ @tree.command(
51
+ name="generate", description="Generates an image based on a text prompt"
52
+ )
53
+ @app_commands.choices(
54
+ aspect_ratio=[
55
+ app_commands.Choice(name="1:1 (Square)", value="1:1"),
56
+ app_commands.Choice(name="9:16 (Vertical)", value="9:16"),
57
+ app_commands.Choice(name="16:9 (Horizontal)", value="16:9"),
58
+ app_commands.Choice(name="4:5 (Portrait)", value="4:5"),
59
+ app_commands.Choice(name="5:4 (Landscape)", value="5:4"),
60
+ app_commands.Choice(name="3:4 (Portrait)", value="3:4"),
61
+ app_commands.Choice(name="4:3 (Landscape)", value="4:3"),
62
+ ]
63
+ )
64
+ async def generate_command(
65
+ interaction: discord.Interaction,
66
+ prompt: str,
67
+ aspect_ratio: app_commands.Choice[str],
68
+ ):
69
  """Generates an image based on the user's prompt and aspect ratio."""
70
+ await interaction.response.defer()
71
 
72
  try:
73
  image_url = generate_image(prompt, aspect_ratio.value)
 
74
  if image_url.startswith("http"):
75
  await interaction.followup.send(
76
  f"Here's your generated image based on the prompt '{prompt}' with aspect ratio {aspect_ratio.name}:\n{image_url}"
77
  )
78
  else:
79
  await interaction.followup.send(
80
+ f"Sorry, I couldn't generate an image. {image_url}"
81
+ )
82
  except Exception as e:
83
  await interaction.followup.send(f"An error occurred: {e}")
84
 
 
 
85
  @tree.command(name="hello", description="Says hello!")
86
  async def hello_command(interaction):
87
  await interaction.response.send_message("Hello there!")
88
 
89
+ # --- Bot Initialization and Event Loop ---
90
+ async def start_bot():
91
+ await client.start(DISCORD_BOT_TOKEN)
92
 
 
93
  async def on_ready():
94
+ await tree.sync()
95
  print("Bot is ready!")
96
 
97
+ client.event(on_ready)
98
 
99
+ def run_bot():
100
+ asyncio.run(start_bot())
101
 
102
+ if __name__ == "__main__":
103
+ # Run the bot in a separate thread
104
+ bot_thread = Thread(target=run_bot)
105
+ bot_thread.start()