【问题标题】:Discord.py Extract user from reactionDiscord.py 从反应中提取用户
【发布时间】:2020-08-03 20:37:40
【问题描述】:

我正在我的机器人中编写一个功能,允许 2 个用户互相决斗,它的工作方式是机器人发送一条消息,告诉每个人准备好,然后在随机数秒后通过机器人反应消息上带有特定的表情符号,决斗中第一个对消息做出反应的人获胜。我的想法很简单,但我不知道如何查看某个用户是否对消息做出了反应。我的问题是 - 这是可能的还是我必须想出另一种方法来解决这个问题?

【问题讨论】:

    标签: python python-3.x discord discord.py discord.py-rewrite


    【解决方案1】:

    wait_for 绝对可以做到这一点,here 记录在案。 wait_for 函数等待event reference 中列出的任何指定事件。

    它接受三个参数EventCheck (optional)timeout(optional)

    文档中有示例,但对您而言,它可能类似于:

    bot = commands.Bot(command_prefix='.', case_insensitive=True)
    
    @bot.command()
    async def game(ctx):
        # Whatever you want here
        msg = await ctx.send("React first to win")
        await msg.add_reaction('?')
    
        def check(reaction, user):
            return str(reaction.emoji) == '?' and user != bot.user
    
        try:
            # Timeout parameter is optional but sometimes can be useful
            reaction, user = await bot.wait_for('reaction_add', timeout=30, check=check)
            
            # Will wait until a user reacts with the specified checks then continue on with the code
            await ctx.send(f"Congratulations {user.name} you won!")
        except asyncio.TimeoutError:
    
            # when wait_for reaches specified timeout duration (in this example it is 30 seconds)
            await ctx.send("You ran out of time!")
    

    Timeout=30 参数是 100% 可选的,您可以将其删除,这样它就会永远等待(或者直到您关闭机器人)。 check 参数也是可选的。

    附:我假设您使用的是 python 3 或更高版本,因此是 F-strings

    【讨论】:

    • 嘿,小问题,我怎么用 cog 写这个,因为我在转换它时遇到了一些麻烦
    • 您可以在函数中添加一个 self 参数,该参数会变成async def game(self, ctx):,并且此代码中的每个bot 实例都会变成self.bot,例如self.bot.wait_for('reaction_add', timeout=30, check=check)
    【解决方案2】:

    是的,这肯定是可能的,有多种方法可以做到这一点,我以前从未尝试过,因为我没有创建任何具有反应功能的机器人,但这应该可以。

    使用on_reaction_add

    @client.event
    async def on_reaction_add(reaction, user):
        channel = client.get_channel('123')
        if reaction.message.channel.id != channel.id:
            return
        else:
            if reaction.emoji == "✅":
                #Do something
                print(user.name)
                print(user.discriminator)
                await channel.send(f"{user} has won the game")
    

    请务必查看 on_reaction_add 文档和 reaction 一个

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      • 2022-08-13
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多