python - 如何取消挂起的 wait_for

标签 python discord discord.py coroutine

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

@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!')

如果用户在实际对消息使用react之前多次发送相同的命令,有什么方法可以取消 wait_for 吗?因此,机器人停止等待对先前发送的消息的 react ,而只等待最后一条消息。

最佳答案

这样的事情对你有用吗?

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!')

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

关于python - 如何取消挂起的 wait_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57673106/

相关文章:

javascript - 查找谁删除了消息

python - Discord.py ' channel 对象没有属性 create_ytdl_player

python - 不和谐 py - message.mentions "else"没有任何结果

python - 聚类边界框并在其上画线(OpenCV、Python)

python - 如何正确构建我的 PyQt GUI 并在传递 ui 时调用函数?

python - SSL 1108 Mac 问题

python-3.x - Discord.py 禁止不在我的服务器中的成员

Python Discord.py - ctx 是必需的参数

python - 搜索文本文件并插入行

python - 重命名数据帧中的索引子集