aboutsummaryrefslogtreecommitdiffstats
path: root/pydis_core
diff options
context:
space:
mode:
authorGravatar shtlrs <[email protected]>2023-07-13 19:59:21 +0100
committerGravatar shtlrs <[email protected]>2024-01-04 13:10:13 +0100
commita3c284e282a60cf7d2fcf84a9e520ded02416471 (patch)
treef5ed80a7c5435e29a94c066dc7e264becba93ec4 /pydis_core
parentDo not attempt to read response body if the HTTP response code is 204. (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')
-rw-r--r--pydis_core/utils/messages.py48
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