【问题标题】:Discord.py - Execute a function in a function while the function is still runningDiscord.py - 在函数仍在运行时执行函数中的函数
【发布时间】:2021-04-19 09:57:31
【问题描述】:

我正在尝试在编辑嵌入的函数中运行计时器函数,同时保持初始函数运行,但我找不到如何做到这一点...这是我的代码:

@bot.command(aliases = ['pc'])
async def pour_combien(ctx, lim, reverse, *gage):

    async def timer(time, msg_to_edit):
        while time >= 0:
            await asyncio.sleep(1)
            embed.set_footer(text=f"• {time} secondes restantes...\n\n\u270B Pour accepter     \u274c Pour annuler (seulement pour le créateur)")
            time -= 1
            await msg_to_edit.edit(embed=embed)

    time = 30.0
    embed = discord.Embed([.......])
    embed.set_footer(text=f"• {time} secondes restantes...\n\n\u270B Pour accepter     \u274c Pour annuler (seulement pour le créateur)")
    demande = await ctx.send(embed= embed)
    await demande.add_reaction("\u270B")
    await demande.add_reaction("\u274c")

    await timer(time, demande)

    while True: 
        try:
            reaction, user = await bot.wait_for('reaction_add', timeout=time, check=lambda reaction, user: reaction.emoji in [u'\u270B',u'\u274c']) 
        except asyncio.TimeoutError:
            return
        else:
            if reaction.emoji == u'\u270B':
                if user != ctx.author:
                    player2 = user
                    break
            else:
                if user == ctx.author:
                    return

所以我想同时运行await timer(time, demande)While True: [...],不知道是否可以。

【问题讨论】:

  • 您正在寻找多线程,或threads。这与 discord.py 无关。只需谷歌搜索线程示例,您应该就能弄清楚

标签: discord.py


【解决方案1】:

您可以使用线程同时运行它们。

import threading

threading.Thread(target=timer, args=[time, msg_to_edit]).start()

【讨论】:

  • 感谢您的回答!但是当我使用线程时,它会调用错误RuntimeWarning: coroutine 'pour_combien.<locals>.timer' was never awaited,但不可能等待线程?...
  • 是的,这是可能的。 bot.loop.create_task(timer(time, msg_to_edit))
【解决方案2】:

您可以使用线程,但为什么要在异步环境中使用。我们可以简单地使用 asyncio。

async def wait_for_reaction_add():
    #while loop here

# inside command
await asyncio.gather(timer(time, demande), wait_for_reaction_add()

asyncio.gather 同时运行两个协程

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2021-02-05
    • 2018-04-08
    • 2013-11-05
    • 1970-01-01
    相关资源
    最近更新 更多