Python discord.Reaction() Examples

The following are 27 code examples of discord.Reaction(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module discord , or try the search function .
Example #1
Source File: help.py    From bot with MIT License 6 votes vote down vote up
def help_cleanup(bot: Bot, author: Member, message: Message) -> None:
    """
    Runs the cleanup for the help command.

    Adds the :trashcan: reaction that, when clicked, will delete the help message.
    After a 300 second timeout, the reaction will be removed.
    """
    def check(reaction: Reaction, user: User) -> bool:
        """Checks the reaction is :trashcan:, the author is original author and messages are the same."""
        return str(reaction) == DELETE_EMOJI and user.id == author.id and reaction.message.id == message.id

    await message.add_reaction(DELETE_EMOJI)

    try:
        await bot.wait_for("reaction_add", check=check, timeout=300)
        await message.delete()
    except TimeoutError:
        await message.remove_reaction(DELETE_EMOJI, bot.user)
    except NotFound:
        pass 
Example #2
Source File: hangman.py    From code-jam-5 with MIT License 4 votes vote down vote up
def to_ascii(reaction: discord.Reaction):
        """
        Converts a Discord reaction emoji into an ASCII character.

        :param reaction: The reaction which the user sent
        :return: The ASCII character corresponding to that reaction
        """
        if reaction.emoji not in UNICODE_LETTERS:
            raise ValueError

        return string.ascii_lowercase[UNICODE_LETTERS.index(reaction.emoji)] 
Example #3
Source File: awaiter.py    From RulesBot with MIT License 4 votes vote down vote up
def emoji_choice(self, text: str, choices: Collection[str]):
        emoji = ''
        while emoji not in choices:
            mes: Message = await self.ctx.send(
                embed=Embed(
                    color=Color.blurple(),
                    description=text))
            for choice in choices:
                await mes.add_reaction(choice)

            def check(reaction: Reaction, user: User):
                message: Message = reaction.message
                return message.channel == self.message.channel and user.id == self.message.author.id

            try:
                reaction, user = await self.bot.wait_for('reaction_add', check=check, timeout=30)
                emoji = str(reaction.emoji)
            except asyncio.TimeoutError:
                raise AwaitTimedOut
        return emoji 
Example #4
Source File: awaiter.py    From RulesBot with MIT License 4 votes vote down vote up
def emoji_reaction(self, text: str) -> PartialEmoji:
        await self.ctx.send(
            embed=Embed(
                color=Color.blurple(),
                description=text))

        def check(reaction: Reaction, user: User):
            message: Message = reaction.message
            return message.channel == self.message.channel and user.id == self.message.author.id

        try:
            reaction, user = await self.bot.wait_for('reaction_add', check=check, timeout=30)
            return reaction
        except asyncio.TimeoutError:
            raise AwaitTimedOut 
Example #5
Source File: togglerole.py    From SML-Cogs with MIT License 4 votes vote down vote up
def on_reaction_add(self, reaction: discord.Reaction, user):
        await self.on_reaction(reaction, user)

    # async def on_reaction_remove(self, reaction: discord.Reaction, user):
    #     await self.on_reaction(reaction, user, remove=True) 
Example #6
Source File: farmers.py    From SML-Cogs with MIT License 4 votes vote down vote up
def handle_reaction(self, reaction: Reaction, user: User):
        """Handle reaction if on farmers menu."""
        if user == self.bot.user:
            return
        if reaction.message.id not in self.reaction_messages:
            return
        if reaction.emoji not in NUMBS.values():
            return
        msg_settings = self.reaction_messages[reaction.message.id]
        if user != msg_settings["author"]:
            return

        message = reaction.message
        reacts = {v: k for k, v in NUMBS.items()}
        react = reacts[reaction.emoji]

        page = self.reaction_messages[message.id]["page"]
        embeds = self.reaction_messages[message.id]["embeds"]
        ctx = self.reaction_messages[message.id]["ctx"]

        if react == "next":
            next_page = 0
            if page == len(embeds) - 1:
                next_page = 0  # Loop around to the first item
            else:
                next_page = page + 1
            self.reaction_messages[message.id]["page"] = next_page
            await self.farmers_menu(
                ctx, embeds, message=message,
                page=next_page)
        elif react == "back":
            next_page = 0
            if page == 0:
                next_page = len(embeds) - 1  # Loop around to the last item
            else:
                next_page = page - 1
            self.reaction_messages[message.id]["page"] = next_page
            await self.farmers_menu(
                ctx, embeds, message=message,
                page=next_page)
        else:
            del self.reaction_messages[message.id]
            await self.bot.clear_reactions(message)
            if not len(self.reaction_messages):
                self.listen_to_reaction = False 
Example #7
Source File: farmers.py    From SML-Cogs with MIT License 4 votes vote down vote up
def on_reaction_remove(self, reaction: Reaction, user: User):
        """Event: on_reaction_remove."""
        if not self.listen_to_reaction:
            return
        await self.handle_reaction(reaction, user) 
Example #8
Source File: farmers.py    From SML-Cogs with MIT License 4 votes vote down vote up
def on_reaction_add(self, reaction: Reaction, user: User):
        """Event: on_reaction_add."""
        if not self.listen_to_reaction:
            return
        await self.handle_reaction(reaction, user) 
Example #9
Source File: pages.py    From NabBot with Apache License 2.0 4 votes vote down vote up
def react_check(self, reaction: discord.Reaction, user: discord.User):
        if user is None or user.id != self.author.id:
            return False

        if reaction.message.id != self.message.id:
            return False
        for (emoji, func) in self.reaction_emojis:
            if str(reaction.emoji) == emoji:
                self.match = func
                return True
        return False 
Example #10
Source File: context.py    From NabBot with Apache License 2.0 4 votes vote down vote up
def react_confirm(self, message: discord.Message, *, timeout=60.0, delete_after=False,
                            use_checkmark=False) -> Optional[bool]:
        """Waits for the command author to reply with a Y or N reaction.

        Returns True if the user reacted with Y
        Returns False if the user reacted with N
        Returns None if the user didn't react at all

        :param message: The message that will contain the reactions.
        :param timeout: The maximum time to wait for reactions
        :param delete_after: Whether to delete or not the message after finishing.
        :param use_checkmark: Whether to use or not checkmarks instead of Y/N
        :return: True if reacted with Y, False if reacted with N, None if timeout.
        """
        if not self.channel.permissions_for(self.me).add_reactions:
            raise RuntimeError('Bot does not have Add Reactions permission.')

        reactions = self.check_reactions if use_checkmark else self.yes_no_reactions
        for emoji in reactions:
            emoji = emoji.replace("<", "").replace(">", "")
            await message.add_reaction(emoji)

        def check_react(reaction: discord.Reaction, user: discord.User):
            if reaction.message.id != message.id:
                return False
            if user.id != self.author.id:
                return False
            if reaction.emoji not in reactions:
                return False
            return True
        try:
            react = await self.bot.wait_for("reaction_add", timeout=timeout, check=check_react)
            if react[0].emoji == reactions[1]:
                return False
        except asyncio.TimeoutError:
            return None
        finally:
            if delete_after:
                await safe_delete_message(message)
            elif self.guild is not None:
                try:
                    await message.clear_reactions()
                except discord.Forbidden:
                    pass
        return True 
Example #11
Source File: egghead_quiz.py    From seasonalbot with MIT License 4 votes vote down vote up
def on_reaction_add(self, reaction: discord.Reaction, user: Union[discord.Member, discord.User]) -> None:
        """Listener to listen specifically for reactions of quiz messages."""
        if user.bot:
            return
        if reaction.message.id not in self.quiz_messages:
            return
        if str(reaction.emoji) not in self.quiz_messages[reaction.message.id]:
            return await reaction.message.remove_reaction(reaction, user)
        if await self.already_reacted(reaction.message, user):
            return await reaction.message.remove_reaction(reaction, user) 
Example #12
Source File: help.py    From seasonalbot with MIT License 4 votes vote down vote up
def on_reaction_add(self, reaction: Reaction, user: User) -> None:
        """Event handler for when reactions are added on the help message."""
        # ensure it was the relevant session message
        if reaction.message.id != self.message.id:
            return

        # ensure it was the session author who reacted
        if user.id != self.author.id:
            return

        emoji = str(reaction.emoji)

        # check if valid action
        if emoji not in REACTIONS:
            return

        self.reset_timeout()

        # Run relevant action method
        action = getattr(self, f'do_{REACTIONS[emoji]}', None)
        if action:
            await action()

        # remove the added reaction to prep for re-use
        with suppress(HTTPException):
            await self.message.remove_reaction(reaction, user) 
Example #13
Source File: snakes_cog.py    From seasonalbot with MIT License 4 votes vote down vote up
def _validate_answer(self, ctx: Context, message: Message, answer: str, options: list) -> None:
        """Validate the answer using a reaction event loop."""
        def predicate(reaction: Reaction, user: Member) -> bool:
            """Test if the the answer is valid and can be evaluated."""
            return (
                reaction.message.id == message.id                  # The reaction is attached to the question we asked.
                and user == ctx.author                             # It's the user who triggered the quiz.
                and str(reaction.emoji) in ANSWERS_EMOJI.values()  # The reaction is one of the options.
            )

        for emoji in ANSWERS_EMOJI.values():
            await message.add_reaction(emoji)

        # Validate the answer
        try:
            reaction, user = await ctx.bot.wait_for("reaction_add", timeout=45.0, check=predicate)
        except asyncio.TimeoutError:
            await ctx.channel.send(f"You took too long. The correct answer was **{options[answer]}**.")
            await message.clear_reactions()
            return

        if str(reaction.emoji) == ANSWERS_EMOJI[answer]:
            await ctx.send(f"{random.choice(CORRECT_GUESS)} The correct answer was **{options[answer]}**.")
        else:
            await ctx.send(
                f"{random.choice(INCORRECT_GUESS)} The correct answer was **{options[answer]}**."
            )

        await message.clear_reactions()
    # endregion

    # region: Commands 
Example #14
Source File: battleship.py    From seasonalbot with MIT License 4 votes vote down vote up
def predicate(
        self,
        ctx: commands.Context,
        announcement: discord.Message,
        reaction: discord.Reaction,
        user: discord.Member
    ) -> bool:
        """Predicate checking the criteria for the announcement message."""
        if self.already_playing(ctx.author):  # If they've joined a game since requesting a player 2
            return True  # Is dealt with later on
        if (
            user.id not in (ctx.me.id, ctx.author.id)
            and str(reaction.emoji) == HAND_RAISED_EMOJI
            and reaction.message.id == announcement.id
        ):
            if self.already_playing(user):
                self.bot.loop.create_task(ctx.send(f"{user.mention} You're already playing a game!"))
                self.bot.loop.create_task(announcement.remove_reaction(reaction, user))
                return False

            if user in self.waiting:
                self.bot.loop.create_task(ctx.send(
                    f"{user.mention} Please cancel your game first before joining another one."
                ))
                self.bot.loop.create_task(announcement.remove_reaction(reaction, user))
                return False

            return True

        if (
            user.id == ctx.author.id
            and str(reaction.emoji) == CROSS_EMOJI
            and reaction.message.id == announcement.id
        ):
            return True
        return False 
Example #15
Source File: exception_handling.py    From jishaku with MIT License 4 votes vote down vote up
def attempt_add_reaction(msg: discord.Message, reaction: typing.Union[str, discord.Emoji])\
        -> typing.Optional[discord.Reaction]:
    """
    Try to add a reaction to a message, ignoring it if it fails for any reason.

    :param msg: The message to add the reaction to.
    :param reaction: The reaction emoji, could be a string or `discord.Emoji`
    :return: A `discord.Reaction` or None, depending on if it failed or not.
    """
    try:
        return await msg.add_reaction(reaction)
    except discord.HTTPException:
        pass 
Example #16
Source File: sigma.py    From apex-sigma-core with GNU General Public License v3.0 4 votes vote down vote up
def on_reaction_remove(self, reaction, user):
        """
        Starts events when a user removes an emote reaction from a message.
        This event is triggered only if the message that had a reaction removed is cached.
        :type reaction: discord.Reaction
        :type user: discord.User
        :param reaction: The reaction that was removed from the message.
        :param user: The user that removed the reaction.
        :return:
        """
        if not user.bot:
            payload = ReactionPayload(self, reaction, user)
            self.loop.create_task(self.queue.event_runner('reaction_remove', payload)) 
Example #17
Source File: sigma.py    From apex-sigma-core with GNU General Public License v3.0 4 votes vote down vote up
def on_reaction_add(self, reaction, user):
        """
        Starts events when a user adds an emote reaction to a message.
        This event is triggered only if the message that had a reaction removed is cached.
        :type reaction: discord.Reaction
        :type user: discord.User
        :param reaction: The reaction that was added to the message.
        :param user: The user that added the reaction.
        :return:
        """
        if not user.bot:
            payload = ReactionPayload(self, reaction, user)
            self.loop.create_task(self.queue.event_runner('reaction_add', payload))
            if str(reaction.emoji) in ['⬅', '➡']:
                self.loop.create_task(self.queue.event_runner('paginate', payload)) 
Example #18
Source File: vote.py    From rubbergod with GNU General Public License v3.0 4 votes vote down vote up
def on_reaction_remove(self, reaction: Reaction, user):
        if self.__handle(reaction.message.id, user.id, reaction.emoji, False,
                         False):
            # print("Already handled")
            return

        # print("Handling")
        await self.voter.handle_reaction(reaction, user, False) 
Example #19
Source File: vote.py    From rubbergod with GNU General Public License v3.0 4 votes vote down vote up
def on_reaction_add(self, reaction: Reaction, user):
        if self.__handle(reaction.message.id, user.id, reaction.emoji, True,
                         False):
            # print("Already handled")
            return

        # print("Handling")
        await self.voter.handle_reaction(reaction, user, True) 
Example #20
Source File: paginator.py    From modmail with GNU Affero General Public License v3.0 4 votes vote down vote up
def react_check(self, reaction: Reaction, user: User) -> bool:
        """

        Parameters
        ----------
        reaction : Reaction
            The `Reaction` object of the reaction.
        user : User
            The `User` or `Member` object of who sent the reaction.

        Returns
        -------
        bool
        """
        return (
            reaction.message.id == self.base.id
            and user.id == self.ctx.author.id
            and reaction.emoji in self.reaction_map.keys()
        ) 
Example #21
Source File: bot.py    From modmail with GNU Affero General Public License v3.0 4 votes vote down vote up
def add_reaction(msg, reaction: discord.Reaction) -> bool:
        if reaction != "disable":
            try:
                await msg.add_reaction(reaction)
            except (discord.HTTPException, discord.InvalidArgument) as e:
                logger.warning("Failed to add reaction %s: %s.", reaction, e)
                return False
        return True 
Example #22
Source File: syncers.py    From bot with MIT License 4 votes vote down vote up
def _reaction_check(
        self,
        author: Member,
        message: Message,
        reaction: Reaction,
        user: t.Union[Member, User]
    ) -> bool:
        """
        Return True if the `reaction` is a valid confirmation or abort reaction on `message`.

        If the `author` of the prompt is a bot, then a reaction by any core developer will be
        considered valid. Otherwise, the author of the reaction (`user`) will have to be the
        `author` of the prompt.
        """
        # For automatic syncs, check for the core dev role instead of an exact author
        has_role = any(constants.Roles.core_developers == role.id for role in user.roles)
        return (
            reaction.message.id == message.id
            and not user.bot
            and (has_role if author.bot else user == author)
            and str(reaction.emoji) in self._REACTION_EMOJIS
        ) 
Example #23
Source File: dialogue_controls.py    From apex-sigma-core with GNU General Public License v3.0 3 votes vote down vote up
def int_dialogue(bot, msg, question, start, end):
    """
    Creates an interactive int dialogue message for a user to react to.
    :param bot: The bot instance associated with this message.
    :type bot: sigma.core.sigma.ApexSigma
    :param msg: The message object to reply to.
    :type msg: discord.Message
    :param question: The embed object to display the interactive int on.
    :type question: discord.Embed
    :param start: The number to start the range at.
    :type start: int
    :param end: The number to end the range at.
    :type end: int
    :return:
    :rtype: (int, bool)
    """
    start = 0 if start < 0 else start
    end = 9 if end > 9 else end
    question.set_author(name=msg.author.display_name, icon_url=user_avatar(msg.author))
    confirmation = await msg.channel.send(embed=question)
    [await confirmation.add_reaction(int_reacts[preac]) for preac in range(start, end + 1)]

    def check_emote(reac, usr):
        """
        Checks for a valid message reaction.
        :param reac: The reaction to validate.
        :type reac: discord.Reaction
        :param usr: The user who reacted to the message.
        :type usr: discord.Member
        :return:
        :rtype: bool
        """
        same_author = usr.id == msg.author.id
        same_message = reac.message.id == confirmation.id
        valid_reaction = str(reac.emoji) in int_reacts
        return same_author and same_message and valid_reaction

    try:
        ae, au = await bot.wait_for('reaction_add', timeout=60, check=check_emote)
        timeout = False
        number = None
        for react_index, int_react in enumerate(int_reacts):
            if int_react == str(ae.emoji):
                number = react_index
                break
    except asyncio.TimeoutError:
        number = None
        timeout = True
    try:
        await confirmation.delete()
    except discord.NotFound:
        pass
    return number, timeout 
Example #24
Source File: dialogue_controls.py    From apex-sigma-core with GNU General Public License v3.0 3 votes vote down vote up
def bool_dialogue(bot, msg, question, tracked=False):
    """
    Creates an interactive bool dialogue message for a user to react to.
    :param bot: The bot instance associated with this message.
    :type bot: sigma.core.sigma.ApexSigma
    :param msg: The message object to reply to.
    :type msg: discord.Message
    :param question: The embed object to display the interactive bool on.
    :type question: discord.Embed
    :param tracked: Whether or not this usage is logged.
    :type tracked: bool
    :return:
    :rtype: (bool, bool)
    """
    question.set_author(name=msg.author.display_name, icon_url=user_avatar(msg.author))
    confirmation = await msg.channel.send(embed=question)
    [await confirmation.add_reaction(preac) for preac in bool_reacts]

    def check_emote(reac, usr):
        """
        Checks for a valid message reaction.
        :param reac: The reaction to validate.
        :type reac: discord.Reaction
        :param usr: The user who reacted to the message.
        :type usr: discord.Member
        :return:
        :rtype: bool
        """
        same_author = usr.id == msg.author.id
        same_message = reac.message.id == confirmation.id
        valid_reaction = str(reac.emoji) in bool_reacts
        return same_author and same_message and valid_reaction

    try:
        start_stamp = arrow.utcnow().float_timestamp
        ae, au = await bot.wait_for('reaction_add', timeout=60, check=check_emote)
        end_stamp = arrow.utcnow().float_timestamp
        if tracked:
            log_usr = f'{msg.author.name}#{msg.author.discriminator} [{msg.author.id}]'
            bot.log.info(f'BOOL DIALOGUE: {log_usr} responded in {round(end_stamp - start_stamp, 5)}s.')
        timeout = False
        if ae.emoji == '✅':
            success = True
        else:
            success = False
    except asyncio.TimeoutError:
        success = False
        timeout = True
    try:
        await confirmation.delete()
    except discord.NotFound:
        pass
    return success, timeout 
Example #25
Source File: candy_collection.py    From seasonalbot with MIT License 3 votes vote down vote up
def on_reaction_add(self, reaction: discord.Reaction, user: discord.Member) -> None:
        """Add/remove candies from a person if the reaction satisfies criteria."""
        message = reaction.message
        # check to ensure the reactor is human
        if user.bot:
            return

        # check to ensure it is in correct channel
        if message.channel.id != Channels.seasonalbot_commands:
            return

        # if its not a candy or skull, and it is one of 10 most recent messages,
        # proceed to add a skull/candy with higher chance
        if str(reaction.emoji) not in ('\N{SKULL}', '\N{CANDY}'):
            if message.id in await self.ten_recent_msg():
                await self.reacted_msg_chance(message)
            return

        for react in self.msg_reacted:
            # check to see if the message id of a message we added a
            # reaction to is in json file, and if nobody has won/claimed it yet
            if react['msg_id'] == message.id and react['won'] is False:
                react['user_reacted'] = user.id
                react['won'] = True
                try:
                    # if they have record/candies in json already it will do this
                    user_records = self.get_candyinfo[user.id]
                    if str(reaction.emoji) == '\N{CANDY}':
                        user_records['record'] += 1
                    if str(reaction.emoji) == '\N{SKULL}':
                        if user_records['record'] <= 3:
                            user_records['record'] = 0
                            lost = 'all of your'
                        else:
                            lost = random.randint(1, 3)
                            user_records['record'] -= lost
                        await self.send_spook_msg(message.author, message.channel, lost)

                except KeyError:
                    # otherwise it will raise KeyError so we need to add them to file
                    if str(reaction.emoji) == '\N{CANDY}':
                        print('ok')
                        d = {"userid": user.id, "record": 1}
                        self.candy_json['records'].append(d)
                await self.remove_reactions(reaction) 
Example #26
Source File: messages.py    From bot with MIT License 3 votes vote down vote up
def wait_for_deletion(
    message: Message,
    user_ids: Sequence[Snowflake],
    deletion_emojis: Sequence[str] = (Emojis.trashcan,),
    timeout: float = 60 * 5,
    attach_emojis: bool = True,
    client: Optional[Client] = None
) -> None:
    """
    Wait for up to `timeout` seconds for a reaction by any of the specified `user_ids` to delete the message.

    An `attach_emojis` bool may be specified to determine whether to attach the given
    `deletion_emojis` to the message in the given `context`

    A `client` instance may be optionally specified, otherwise client will be taken from the
    guild of the message.
    """
    if message.guild is None and client is None:
        raise ValueError("Message must be sent on a guild")

    bot = client or message.guild.me

    if attach_emojis:
        for emoji in deletion_emojis:
            await message.add_reaction(emoji)

    def check(reaction: Reaction, user: Member) -> bool:
        """Check that the deletion emoji is reacted by the appropriate user."""
        return (
            reaction.message.id == message.id
            and str(reaction.emoji) in deletion_emojis
            and user.id in user_ids
        )

    with contextlib.suppress(asyncio.TimeoutError):
        await bot.wait_for('reaction_add', check=check, timeout=timeout)
        await message.delete() 
Example #27
Source File: snekbox.py    From bot with MIT License 3 votes vote down vote up
def predicate_eval_emoji_reaction(ctx: Context, reaction: Reaction, user: User) -> bool:
    """Return True if the reaction REEVAL_EMOJI was added by the context message author on this message."""
    return reaction.message.id == ctx.message.id and user.id == ctx.author.id and str(reaction) == REEVAL_EMOJI