artintel235 commited on
Commit
dda26c7
·
verified ·
1 Parent(s): 5b0ec8c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -64
app.py CHANGED
@@ -1,82 +1,63 @@
1
  import os
 
2
  import discord
3
  from discord.ext import commands
4
- import requests
5
- from fastapi import FastAPI
6
- from fastapi.middleware.cors import CORSMiddleware
7
- import threading
8
- from contextlib import asynccontextmanager
9
 
10
- # Load the bot token and API key from environment variables
11
- DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
12
- GLIF_API_KEY = os.getenv("GLIF_API_KEY")
13
  GLIF_API_URL = "https://simple-api.glif.app"
14
 
15
- # Discord bot setup
16
- intents = discord.Intents.default()
17
- bot = commands.Bot(command_prefix="!", intents=intents)
18
-
19
- # FastAPI app
20
- app = FastAPI()
21
-
22
- # Enable CORS if necessary
23
- app.add_middleware(
24
- CORSMiddleware,
25
- allow_origins=["*"],
26
- allow_credentials=True,
27
- allow_methods=["*"],
28
- allow_headers=["*"],
29
- )
30
-
31
  # Function to call the GLIF API
32
  def generate_image(prompt):
33
- aspect_ratio = "9:16" # Hardcoded aspect ratio
 
 
 
34
  payload = {
35
- "id": "cm3ugmzv2002gnckiosrwk6xi", # Your GLIF ID
36
- "inputs": [prompt, aspect_ratio]
 
 
 
 
 
37
  }
38
- headers = {"Authorization": f"Bearer {GLIF_API_KEY}"}
39
- try:
40
- response = requests.post(GLIF_API_URL, json=payload, headers=headers)
41
- if response.status_code == 200:
42
- response_data = response.json()
43
- if "output" in response_data:
44
- return response_data["output"] # Image URL
45
- elif "error" in response_data:
46
- return f"Error: {response_data['error']}"
47
- else:
48
- return f"API request failed with status code: {response.status_code}"
49
- except Exception as e:
50
- return f"Error: {str(e)}"
51
 
52
- # Discord bot commands
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  @bot.command(name="generate")
54
  async def generate(ctx, *, prompt: str):
55
- await ctx.send(f"Generating an image for: `{prompt}`...")
 
 
 
56
  image_url = generate_image(prompt)
 
57
  if image_url.startswith("http"):
58
- await ctx.send(image_url) # Send the image URL
59
  else:
60
  await ctx.send(f"Failed to generate image: {image_url}")
61
 
62
- @bot.event
63
- async def on_ready():
64
- print(f"Logged in as {bot.user}")
65
-
66
- # Define an async context manager for the lifespan event
67
- @asynccontextmanager
68
- async def lifespan(app: FastAPI):
69
- # Start the bot thread during startup
70
- thread = threading.Thread(target=bot.run, args=(DISCORD_BOT_TOKEN,), daemon=True)
71
- thread.start()
72
- yield # Application lifecycle continues here
73
- # Optionally handle cleanup here if needed
74
- print("FastAPI application is shutting down")
75
-
76
- # Use the lifespan handler in the FastAPI app
77
- app.lifespan = lifespan
78
-
79
- # Health check endpoint
80
- @app.get("/")
81
- def health_check():
82
- return {"status": "Bot is running!"}
 
1
  import os
2
+ import requests
3
  import discord
4
  from discord.ext import commands
 
 
 
 
 
5
 
6
+ # GLIF Simple API endpoint
 
 
7
  GLIF_API_URL = "https://simple-api.glif.app"
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  # Function to call the GLIF API
10
  def generate_image(prompt):
11
+ # Hardcoded aspect ratio (9:16)
12
+ aspect_ratio = "9:16"
13
+
14
+ # Prepare the payload for the GLIF API
15
  payload = {
16
+ "id": "cm3ugmzv2002gnckiosrwk6xi", # Glif ID
17
+ "inputs": [prompt, aspect_ratio] # Passing the prompt and the fixed aspect ratio
18
+ }
19
+
20
+ # Set up headers with the API token
21
+ headers = {
22
+ "Authorization": f"Bearer {os.getenv('GLIF_API_KEY')}"
23
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ # Make the request to the GLIF API
26
+ response = requests.post(GLIF_API_URL, json=payload, headers=headers)
27
+
28
+ if response.status_code == 200:
29
+ # Parse the response
30
+ response_data = response.json()
31
+ if "output" in response_data:
32
+ # Return the image URL
33
+ return response_data["output"]
34
+ elif "error" in response_data:
35
+ # Handle errors (even though the status code is 200)
36
+ return f"Error: {response_data['error']}"
37
+ else:
38
+ return f"API request failed with status code: {response.status_code}"
39
+
40
+ # Initialize the Discord bot
41
+ intents = discord.Intents.default()
42
+ intents.message_content = True
43
+ bot = commands.Bot(command_prefix="!", intents=intents)
44
+
45
+ @bot.event
46
+ async def on_ready():
47
+ print(f'Logged in as {bot.user.name}')
48
+
49
  @bot.command(name="generate")
50
  async def generate(ctx, *, prompt: str):
51
+ """Generate an image based on the provided prompt."""
52
+ await ctx.send(f"Generating image for prompt: {prompt}...")
53
+
54
+ # Call the GLIF API to generate the image
55
  image_url = generate_image(prompt)
56
+
57
  if image_url.startswith("http"):
58
+ await ctx.send(image_url)
59
  else:
60
  await ctx.send(f"Failed to generate image: {image_url}")
61
 
62
+ # Run the bot
63
+ bot.run(os.getenv('DISCORD_BOT_TOKEN'))