diff options
author | 2023-07-13 19:59:21 +0100 | |
---|---|---|
committer | 2023-07-13 19:59:21 +0100 | |
commit | aa01202d65462681678919bfa07bf44b5f0a682c (patch) | |
tree | eaa0e234452f14e728d851408e41e235414b7984 /pydis_core/utils/messages.py | |
parent | Update expiry label from 1 month to 30 days (#185) (diff) |
port reaction_check in a new `messages` util
This is because it's a component that can be reused by all bots.
Diffstat (limited to 'pydis_core/utils/messages.py')
-rw-r--r-- | pydis_core/utils/messages.py | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/pydis_core/utils/messages.py b/pydis_core/utils/messages.py new file mode 100644 index 00000000..8653164b --- /dev/null +++ b/pydis_core/utils/messages.py @@ -0,0 +1,48 @@ +from typing import Sequence + +from pydis_core.utils.logging import get_logger +from pydis_core.utils.scheduling import create_task + +import discord + + +log = get_logger(__name__) + + +def reaction_check( + reaction: discord.Reaction, + user: discord.abc.User, + *, + message_id: int, + allowed_emoji: Sequence[str], + allowed_users: Sequence[int], + allowed_roles: Sequence[int] | None = None, +) -> bool: + """ + Check if a reaction's emoji and author are allowed and the message is `message_id`. + + If the user is not allowed, remove the reaction. Ignore reactions made by the bot. + If `allow_mods` is True, allow users with moderator roles even if they're not in `allowed_users`. + """ + right_reaction = ( + not user.bot + and reaction.message.id == message_id + and str(reaction.emoji) in allowed_emoji + ) + if not right_reaction: + return False + + allowed_roles = allowed_roles or [] + has_sufficient_roles = any(role.id in allowed_roles for role in getattr(user, "roles", [])) + + if user.id in allowed_users or has_sufficient_roles: + log.trace(f"Allowed reaction {reaction} by {user} on {reaction.message.id}.") + return True + + log.trace(f"Removing reaction {reaction} by {user} on {reaction.message.id}: disallowed user.") + create_task( + reaction.message.remove_reaction(reaction.emoji, user), + suppressed_exceptions=(discord.HTTPException,), + name=f"remove_reaction-{reaction}-{reaction.message.id}-{user}" + ) + return False |