python - 如何让异步函数在后台运行?

标签 python python-3.6 discord.py

我不知道如何使异步函数不阻塞下一行代码/防止循环从顶部重新开始。

异步函数:

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/

相关文章:

python - 在数据框中显示 NER Spacy 数据

python - 变量在 lambda 函数内如何工作?

python - 如何格式化 float 的输出,使其在小数点后有两位?

python - 从 discord 使用 FFmpegPCMAudio 的问题

python - 如何让我的 Discord 机器人每周日在 0 :00? 运行一个函数

python - on_message函数重复,Discord.py重写

python - 密集层中的多个 Softmax

python - 在 postgresql 的 python 中使用 COPY 而不是 INSERT

python - ImageDataGenerator流函数的正确使用

python - 如何将前导数字添加到空列表中并用输入填充它