所以我的 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())
注意:两个协程的完成之间可能会有一点延迟。
引用文献:
关于python - 在我的不和谐机器人上同时运行两个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66620313/