在我的discord机器人上同时运行两个循环

2024-10-03 19:19:42 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,python中的discord bot的任务是在用户发送消息“$start”后立即发送嵌入。在此之后,代码将启动while循环并检查用户是否有反应。同时,我想每秒钟编辑一次机器人的消息,这样我就可以显示某种计时器,向用户显示他们还有多少时间可以做出反应,但我不知道如何实现同时运行的计时器。在这个问题上使用multiprocessing有用吗? 如果有人需要它来回答我的问题,下面是我非常具体的代码:)

@client.command()
async def start(ctx):
    timer = 120
    remTime = timer
    seedCapital = 10000
    sessionEmpty = True

players[ctx.author] = seedCapital

em = discord.Embed(title = "New Poker Session", description = "Waiting for players to join ...\nreact with 💸 to join or ▶️ to start (only host)", color = discord.Color.green())
#em.add_field(name = "2 minutes remaining from now on!", value = "")
botMsg = await ctx.send(embed = em)
await botMsg.add_reaction("💸")
await botMsg.add_reaction("▶️")

while True:
    mom0 = time.perf_counter()
    try:
        reaction, user = await client.wait_for('reaction_add', timeout = remTime, check = lambda reaction, user: reaction.emoji in ["💸", "▶️"])
        #msg = await client.wait_for('message', timeout = remTime, check = lambda m: m.channel == ctx.channel)
        #print(f"receiving message: {msg.content}")
    except asyncio.TimeoutError:
        break

    if reaction.emoji == "💸":
        sessionEmpty = False
        await ctx.send(f"{user.mention} joined the session!")
        players[user] = seedCapital
    elif user == ctx.author and reaction.emoji == "▶️":
        break

    mom1 = time.perf_counter()
    neededTime = mom1 - mom0
    remTime -= neededTime
    print(remTime)

if not sessionEmpty:
    await ctx.send("starting session ...")
    #start session
else:
    await ctx.send("Noone joined your session :(")

Tags: clientsendaddsessionawaitstartctxem
1条回答
网友
1楼 · 发布于 2024-10-03 19:19:42

我们可以使用asyncio.gather并发运行协同路由

#after command
from datetime import datetime, timedelta

end_time = datetime.now() + timedelta(seconds=30) #30 seconds to react

async def coro():
   for i in range(30, 0, 5):
       await botMsg.edit(f'time remaining: {i}') #send another message if you don't want old content to be erased
       await asyncio.sleep(5)

async def coro2():
   while datetime.now() <= endtime:
      #do stuff

await asyncio.gather(coro(), coro2())

注意:在完成两个协程之间可能会有一点延迟

参考资料:

编辑:这是我提到的小延迟Open In Colab

相关问题 更多 >