Skip to content

Commit a3c284e

Browse files
committed
port reaction_check in a new messages util
This is because it's a component that can be reused by all bots.
1 parent 8877fa1 commit a3c284e

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

pydis_core/utils/messages.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
from typing import Sequence
2+
3+
from pydis_core.utils.logging import get_logger
4+
from pydis_core.utils.scheduling import create_task
5+
6+
import discord
7+
8+
9+
log = get_logger(__name__)
10+
11+
12+
def reaction_check(
13+
reaction: discord.Reaction,
14+
user: discord.abc.User,
15+
*,
16+
message_id: int,
17+
allowed_emoji: Sequence[str],
18+
allowed_users: Sequence[int],
19+
allowed_roles: Sequence[int] | None = None,
20+
) -> bool:
21+
"""
22+
Check if a reaction's emoji and author are allowed and the message is `message_id`.
23+
24+
If the user is not allowed, remove the reaction. Ignore reactions made by the bot.
25+
If `allow_mods` is True, allow users with moderator roles even if they're not in `allowed_users`.
26+
"""
27+
right_reaction = (
28+
not user.bot
29+
and reaction.message.id == message_id
30+
and str(reaction.emoji) in allowed_emoji
31+
)
32+
if not right_reaction:
33+
return False
34+
35+
allowed_roles = allowed_roles or []
36+
has_sufficient_roles = any(role.id in allowed_roles for role in getattr(user, "roles", []))
37+
38+
if user.id in allowed_users or has_sufficient_roles:
39+
log.trace(f"Allowed reaction {reaction} by {user} on {reaction.message.id}.")
40+
return True
41+
42+
log.trace(f"Removing reaction {reaction} by {user} on {reaction.message.id}: disallowed user.")
43+
create_task(
44+
reaction.message.remove_reaction(reaction.emoji, user),
45+
suppressed_exceptions=(discord.HTTPException,),
46+
name=f"remove_reaction-{reaction}-{reaction.message.id}-{user}"
47+
)
48+
return False

0 commit comments

Comments
 (0)