python - 在我的不和谐机器人上同时运行两个循环

标签 python discord.py bots python-asyncio

所以我的 python 中的不和谐机器人的任务是在用户发送消息“$start”后立即发送嵌入。之后,代码启动 while 循环并检查用户是否使用react。同时,我想每秒编辑机器人的消息,这样我就可以显示某种计时器来向用户显示他们还剩下多少时间来使用react,但我不知道如何实现同时运行的计时器。对于这个问题使用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 :(")

最佳答案

我们可以使用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

关于python - 在我的不和谐机器人上同时运行两个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66620313/

相关文章:

python - 允许谷歌应用程序的权限后无法连接到本地主机

facebook - 如何为 Facebook Messenger 创建群组机器人?

Facebook 爬虫机器人崩溃网站

python - discord.py 为什么 @client.command 不起作用?

Python:打印每行的范围

带边框的 python str.replace()

python - 将大文件加载到 Flask 中

python - 禁止(状态代码 : 403) Can't send messages to this user

python - discord.py(python)中的ffmpeg播放器自动离开

Discord.py 重写获取公会成员列表