我不知道如何使异步函数不阻塞下一行代码/防止循环从顶部重新开始。
异步函数:
async def updateEmbed(self, ctx, obj: discord.Message):
while self.bot.toggle[ctx.guild.id] == 1:
mainembed = discord.Embed(title='Current Servers', colour=discord.Colour.purple(), timestamp=datetime.datetime.utcnow())
result = [[f'{key} | ({len(value)} players)', *value] for key, value in self.bot.scrimmatches[ctx.guild.id].items()]
for x in result:
people = []
for aperson in x[1:]:
person = self.bot.get_user(aperson)
people.append(f'{person.mention}\n')
mainembed.add_field(name=x[0], value=(''.join(people)))
await obj.edit(embed=mainembed)
await asyncio.sleep(5)
主要命令:
self.bot.toggle[ctx.guild.id] = 0
async with async_timeout.timeout(length):
try:
while True:
msg = await self.bot.wait_for('message', check=check)
await tryRemoveUser(self, ctx, user=msg.author)
try:
self.bot.scrimmatches[msg.guild.id][((msg.content).upper())].append(msg.author.id)
except:
self.bot.scrimmatches[msg.guild.id] = ((msg.content).upper())
if self.bot.toggle[ctx.guild.id] == 0:
self.bot.toggle[ctx.guild.id] = 1
await updateEmbed(self, ctx, obj=history)
except:
pass
在主命令上,我希望 while True 循环再次启动,但是循环卡在 updateEmbed 函数的 while 循环中,因此它停止读取消息,因为循环不重复。
最佳答案
我不确定你在用那些令人讨厌的代码做什么,但你的 updateEmbed
方法永远不会停止,直到 while self.bot.toggle[ctx.guild.id] == 1:
是正确的。
看看你写的这段代码:
if self.bot.toggle[ctx.guild.id] == 0:
self.bot.toggle[ctx.guild.id] = 1
await updateEmbed(self, ctx, obj=history)
首先将 self.bot.toggle[ctx.guild.id]
设置为 1,然后调用 await updateEmbed(self, ctx, obj=history)
永远不会结束,因为它有无限循环:
while self.bot.toggle[ctx.guild.id] == 1:
这始终是正确的,因此会永远循环,因为您永远不会将 self.bot.toggle[ctx.guild.id]
更改为其他值。
不要做一些令人讨厌的无限循环,而是前往 Discord.Py rewrite API reference并使用events
关于python - 如何让异步函数在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55563397/