首页 > 解决方案 > 如何从反应中正确获取用户列表?

问题描述

我目前正在尝试创建一个 Discord Bot,将人们随机分成 2 个团队。现在我能够发送带有反应的消息,然后返回对机器人消息做出反应的用户列表。但我面临以下问题:

  1. 该列表包括机器人;
  2. 该列表仅包括机器人和对消息做出反应的第一人(我想在我击中不包括机器人的 10 名玩家后立即随机化)
  3. 我需要将列表分成两个团队
if str(reaction.emoji) == '✅': ## right now this is just selecting the game
    def check(reaction, user): ## this check is here but I was unable to properly use it without breaking the code, or even defining the limit of 10 reactions
        return user != bot.user and (str(reaction.emoji) == '')

    msg_players1 = await ctx.send('Summoners, react below: ')
    await msg_players1.add_reaction('')
    msg_players1 = await ctx.channel.fetch_message(msg_players1.id)
    reactions = msg_players1.reactions
    users = set()
    
    for reactions in user, reaction:
        async for user in reaction.users():
            users.add(user)

    await ctx.send(f"time 1: {', '.join(user.name for user in users)}")

我对编码很陌生,对 Discord 机器人更是如此,非常感谢任何帮助!谢谢!

编辑:我刚刚测试过,它没有返回对表情符号做出反应的用户名,而是返回调用命令的用户名

标签: pythondiscorddiscord.py

解决方案


一旦您添加了对消息的反应,您就会获取消息,用户没有足够的时间对其做出反应。您可以睡x几秒钟并获取消息,但这是一个非常糟糕的主意,您必须猜测要给 10 个用户多少时间做出反应。

相反,您可以使用 while 循环,等待确切的 10 个反应(不包括机器人)并继续。

users = set() 

def check(reaction, user):
    return str(reaction) == "✅" and user != bot.user  # or `client.user`, however you named it

while len(users) < 10:
    reaction, user = await bot.wait_for("reaction_add", check=check)
    users.add(user)

# once here, divide the `users` set into teams

参考:


推荐阅读