Discord.py重写命令中的反应处理

时间:2019-11-03 19:51:27

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

有没有一种方法可以捕获命令中的反应。我已经发出了删除通道的命令,但是我想问用户是否确定使用响应。我想防止其他人对此消息做出反应(只有上下文作者可以做出反应)。

到目前为止,我发现仅使用on_reaction_add(),但这无法检测到发送命令的用户。我只想在消息作者是对消息作出反应的人的情况下更新命令,其他任何人都可以忽略它。

更新:我发现wait_for()确实可以满足我的要求,但是现在的问题是如何检查是否设置了错误的响应? (即,如果我按第二个反应,请删除该消息)

    if is_admin:
        msg = await ctx.send('Clear: Are you sure you would like to purge this entire channel?')
        emoji1 = u"\u2705"
        emoji2 = u"\u274E"
        await msg.add_reaction(emoji=emoji1)
        await msg.add_reaction(emoji=emoji2)

        def check(reaction, user):
            return user == ctx.message.author and reaction.emoji == u"\u2705"

        try:
            reaction, user = await self.client.wait_for('reaction_add', timeout=10.0, check=check)
        except asyncio.TimeoutError:
            return await msg.delete()
        else:
            channel = ctx.message.channel
            new_channel = await channel.clone(name=channel.name, reason=f'Clear Channel ran by {ctx.message.author.name}')
            await new_channel.edit(position=channel.position)
            await channel.delete(reason=f'Clear Channel ran by {ctx.message.author.name}')
            await new_channel.send('Clear: Channel has now been cleared.', delete_after=7)
    else:
        await ctx.send(f"Sorry, you do not have access to this command.", delete_after=5)

1 个答案:

答案 0 :(得分:1)

这是我用来为check生成wait_for函数的函数:

from collections.abc import Sequence

def make_sequence(seq):
    if seq is None:
        return ()
    if isinstance(seq, Sequence) and not isinstance(seq, str):
        return seq
    else:
        return (seq,)

def reaction_check(message=None, emoji=None, author=None, ignore_bot=True):
    message = make_sequence(message)
    message = tuple(m.id for m in message)
    emoji = make_sequence(emoji)
    author = make_sequence(author)
    def check(reaction, user):
        if ignore_bot and user.bot:
            return False
        if message and reaction.message.id not in message:
            return False
        if emoji and reaction.emoji not in emoji:
            return False
        if author and user not in author:
            return False
        return True
    return check

我们可以传递要等待的消息,用户和表情符号,它将自动忽略其他所有内容。

check = reaction_check(message=msg, author=ctx.author, emoji=(emoji1, emoji2))
try: 
    reaction, user = await self.client.wait_for('reaction_add', timeout=10.0, check=check)
    if reaction.emoji == emoji1:
        # emoji1 logic
    elif reaction.emoji == emoji2:
        # emoji2 logic
except TimeoutError:
    # timeout logic