lunarflu HF Staff commited on
Commit
fad843f
·
1 Parent(s): 3da968f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -5
app.py CHANGED
@@ -17,6 +17,9 @@ intents.message_content = True
17
 
18
  bot = commands.Bot(command_prefix='!', intents=intents)
19
 
 
 
 
20
 
21
  async def jojo(ctx):
22
  start_time = time.time()
@@ -28,19 +31,40 @@ async def jojo(ctx):
28
  await ctx.send(f"{style} image generated in {generation_time:.2f} seconds.")
29
  await ctx.send(file=discord.File(im))
30
 
 
 
 
 
 
 
31
 
32
  @bot.command()
33
  async def command(ctx, num_requests: int):
34
- tasks = []
 
 
 
 
 
 
 
35
 
 
36
  for _ in range(num_requests):
37
- task = asyncio.create_task(jojo(ctx))
38
- tasks.append(task)
39
 
40
- await asyncio.gather(*tasks)
41
- await ctx.send("Command executed.")
42
 
 
 
 
43
 
 
 
 
 
 
44
  def run_bot():
45
  bot.run(DISCORD_TOKEN)
46
 
 
17
 
18
  bot = commands.Bot(command_prefix='!', intents=intents)
19
 
20
+ MAX_WORKERS = 5
21
+
22
+ worker_semaphore = asyncio.Semaphore(MAX_WORKERS)
23
 
24
  async def jojo(ctx):
25
  start_time = time.time()
 
31
  await ctx.send(f"{style} image generated in {generation_time:.2f} seconds.")
32
  await ctx.send(file=discord.File(im))
33
 
34
+ async def process_requests(queue):
35
+ while True:
36
+ ctx = await queue.get()
37
+ async with worker_semaphore:
38
+ await jojo(ctx)
39
+ queue.task_done()
40
 
41
  @bot.command()
42
  async def command(ctx, num_requests: int):
43
+ start_time = time.time()
44
+ queue = asyncio.Queue()
45
+
46
+ # Start the worker tasks
47
+ worker_tasks = []
48
+ for _ in range(MAX_WORKERS):
49
+ task = asyncio.create_task(process_requests(queue))
50
+ worker_tasks.append(task)
51
 
52
+ # Add the requests to the queue
53
  for _ in range(num_requests):
54
+ await queue.put(ctx)
 
55
 
56
+ # Wait for all requests to be processed
57
+ await queue.join()
58
 
59
+ # Cancel the worker tasks
60
+ for task in worker_tasks:
61
+ task.cancel()
62
 
63
+ await ctx.send("Command executed.")
64
+ end_time = time.time()
65
+ generation_time = end_time - start_time
66
+ await ctx.send(f"{style} everything done in {generation_time:.2f} seconds.")
67
+
68
  def run_bot():
69
  bot.run(DISCORD_TOKEN)
70