【发布时间】:2020-12-16 16:30:00
【问题描述】:
我目前正在尝试为我的 Discord Bot 实现一个功能,我可以在设定的几秒钟后轻松删除发送的消息。
这是我的功能:
async def messageCountdown(context, message, counter):
response = await context.send(f"**{'—' * counter}** \n {message}")
for i in range(counter, 0, -1):
await response.edit(content=f"**{'—' * i}** \n {message}")
await asyncio.sleep(1)
await context.message.delete()
await response.delete()
函数调用:
@client.command()
async def test(context, *message):
await messageCountdown(context, "Test", 10)
如果只调用一次,函数本身就可以运行得很好:
https://gyazo.com/3b1eef9ecf8ecbe6473e8b20dfcd19d1
一旦我调用它两次或更多次,倒计时就会以一种奇怪的方式不一致:https://gyazo.com/af4b23c5831ae90d5bc5a8461a22b0d7
我再次尝试了相同的操作,但将await asyncio.sleep(1) 替换为time.sleep(1),结果相同。
这是我不知道如何继续的地方,因为我发现asyncio 应该可以解决问题,但显然不能。另外,我不明白为什么一个函数会阻塞相反的函数,因为 asyncio 和 time 都不应该这样做,因为该函数是异步的(这应该完全阻止现在发生的事情,不是吗?)。
【问题讨论】:
标签: python asynchronous async-await discord.py