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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -7
app.py CHANGED
@@ -3,7 +3,9 @@ import discord
3
  from discord.ext import commands
4
  import requests
5
  from fastapi import FastAPI
 
6
  import threading
 
7
 
8
  # Load the bot token and API key from environment variables
9
  DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
@@ -17,6 +19,15 @@ bot = commands.Bot(command_prefix="!", intents=intents)
17
  # FastAPI app
18
  app = FastAPI()
19
 
 
 
 
 
 
 
 
 
 
20
  # Function to call the GLIF API
21
  def generate_image(prompt):
22
  aspect_ratio = "9:16" # Hardcoded aspect ratio
@@ -52,14 +63,18 @@ async def generate(ctx, *, prompt: str):
52
  async def on_ready():
53
  print(f"Logged in as {bot.user}")
54
 
55
- # Function to run the bot in a separate thread
56
- def run_bot():
57
- bot.run(DISCORD_BOT_TOKEN)
 
 
 
 
 
 
58
 
59
- # Start the bot thread when FastAPI starts
60
- @app.on_event("startup")
61
- def startup_event():
62
- threading.Thread(target=run_bot, daemon=True).start()
63
 
64
  # Health check endpoint
65
  @app.get("/")
 
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")
 
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
 
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("/")