【问题标题】:How can I make an async function run in the background?如何让异步函数在后台运行?
【发布时间】:2019-08-29 00:15:33
【问题描述】:

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

异步函数:

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 循环中,因此它停止读取消息,因为循环不重复。

【问题讨论】:

    标签: python python-3.6 discord.py discord.py-rewrite


    【解决方案1】:

    我不确定你在用那个讨厌的代码做什么,但你的 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 2016-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多