首页 > 解决方案 > Discord.py:我如何让机器人获取在给定时间内对消息做出反应的用户列表

问题描述

我正在 python 3.8.6 上制作一个 discord.py 机器人。

我希望这个特定的功能以特定的方式工作......

代码-

@bot.command()
async def command_name(ctx, function):


    #code for function 1

    #code for function 2

        # making the embed

        message = await ctx.send(embed=e)
        await message.add_reaction('✅')

        def check(reaction, user):
            if user not in players and not user.bot:
                players.append(user.mention)
            return reaction.message == message and str(reaction.emoji) == '✅'

        try:
            await bot.wait_for('reaction_add', timeout=10, check=check)

        except asyncio.TimeoutError:
            await ctx.send('time is up, and not enough players')

        else:
            await ctx.send(players) 
            # further code

问题:机器人立即发送列表玩家

问题:我可以添加什么让它等待 30 秒,将列表附加到对嵌入做出反应的用户,然后发送列表,如果 30 秒后 len(players) 不是 3 或更多发送 -

await ctx.send('time is up, and not enough players')

标签: pythonasync-awaitdiscord.py

解决方案


问题是await bot.wait_for('reaction_add', timeout=10, check=check)在做出的第一个反应中进行。在这种情况下,机器人反应会立即触发此事件,因此将返回一个空列表。

我想到了两个选择:

  1. 使检查函数始终返回 False,但仍附加用户。这样,wait_for 函数将保持活动状态,直到超时,然后引发异常。在 except 块中继续您的代码或传递它。
  2. 等待 30 秒,然后再次获取消息并附加所有对复选标记做出反应的用户。

第一个选项:

@client.command()
async def command_name(ctx):

    players = []

    message = await ctx.send("Message")
    await message.add_reaction('✅')

    def check(reaction, user):
        if user not in players and not user.bot:
            players.append(user.mention)
        return False

    try:
        await client.wait_for('reaction_add', timeout=30, check=check)

    except asyncio.TimeoutError:
        pass

    if len(players) < 3:
        await ctx.send('Time is up, and not enough players')
    else:
        await ctx.send(players) 

第二个(首选)选项:

@client.command()
async def command_name(ctx):

    players = []

    message = await ctx.send("Message")
    await message.add_reaction('✅')
    await asyncio.sleep(30)

    message = await ctx.fetch_message(message.id)

    for reaction in message.reactions:
        if reaction.emoji == '✅':
            async for user in reaction.users():
                if user != client.user:
                    players.append(user.mention)

    if len(players) < 3:
        await ctx.send('Time is up, and not enough players')
    else:
        await ctx.send(players)

API的引用:
fetch_message
reaction.users()


推荐阅读