【问题标题】:How to cancel a pending wait_for如何取消挂起的 wait_for
【发布时间】:2019-12-31 13:00:48
【问题描述】:

假设一个类似这样的命令:

@bot.command()
async def test(ctx):
    def check(r, u):
        return u == ctx.message.author and r.message.channel == ctx.message.channel and str(r.emoji) == '✅'

    await ctx.send("React to this with ✅")
    try:
        reaction, user = await bot.wait_for('reaction_add', timeout=300.0, check=check)
    except asyncio.TimeoutError:
        await ctx.send('Timeout')
    else:
        await ctx.send('Cool, thanks!')

如果用户在对消息做出实际反应之前多次发送相同的命令,是否有任何方法可以取消 wait_for?因此,机器人停止等待对先前发送的消息的反应,而只等待最后一条。

【问题讨论】:

标签: python discord discord.py coroutine


【解决方案1】:

这样的东西对你有用吗?

pending_tasks = dict()

async def test(ctx):
    def check(r, u):
        return u == ctx.message.author and r.message.channel == ctx.message.channel and str(r.emoji) == '✅'

    await ctx.send("React to this with ✅")
    try:
        if ctx.message.author in pending_tasks:
            pending_tasks[ctx.message.author].close()
        pending_tasks[ctx.message.author] = bot.wait_for('reaction_add', timeout=300.0, check=check)
        reaction, user = await pending_tasks[ctx.message.author]
    except asyncio.TimeoutError:
        await ctx.send('Timeout')
    else:
        await ctx.send('Cool, thanks!')

您将所有未决请求存储在一个字典中,并在创建另一个请求之前检查您是否已经有该用户的现有任务,如果您取消它并创建一个新任务

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    相关资源
    最近更新 更多