Skip to content

Commit

Permalink
Merge branch 'main' into actions-tracking
Browse files Browse the repository at this point in the history
  • Loading branch information
CarrotManMatt committed Jul 11, 2024
2 parents 3644b2b + 31817e4 commit 11830f7
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 25 deletions.
49 changes: 24 additions & 25 deletions cogs/strike.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,10 @@
from logging import Logger
from typing import Final

import aiohttp
import discord

# noinspection SpellCheckingInspection
from asyncstdlib.builtins import any as asyncany
from discord import Webhook
from discord.ui import View

from config import settings
Expand Down Expand Up @@ -418,19 +416,13 @@ async def get_confirmation_message_channel(self, user: discord.User | discord.Me
"""
if settings["MANUAL_MODERATION_WARNING_MESSAGE_LOCATION"] == "DM":
if user.bot:
session: aiohttp.ClientSession
with aiohttp.ClientSession() as session: # type: ignore[assignment]
log_confirmation_message_channel: discord.TextChannel | None = (
await Webhook.from_url(
settings["DISCORD_LOG_CHANNEL_WEBHOOK_URL"],
session=session,
).fetch()
).channel

if not log_confirmation_message_channel:
raise StrikeTrackingError

return log_confirmation_message_channel
fetch_log_channel_error: RuntimeError
try:
return await self.bot.fetch_log_channel()
except RuntimeError as fetch_log_channel_error:
raise StrikeTrackingError(
str(fetch_log_channel_error),
) from fetch_log_channel_error

raw_user: discord.User | None = (
self.bot.get_user(user.id)
Expand Down Expand Up @@ -478,17 +470,19 @@ async def _confirm_manual_add_strike(self, strike_user: discord.User | discord.M
after=discord.utils.utcnow() - datetime.timedelta(minutes=1),
action=action,
)
if _audit_log_entry.target == strike_user
if _audit_log_entry.target.id == strike_user.id # NOTE: IDs are checked here rather than the objects themselves as the audit log provides an unusual object type in some cases.
)
except (StopIteration, StopAsyncIteration):
IRRETRIEVABLE_AUDIT_LOG_MESSAGE: Final[str] = (
f"Unable to retrieve audit log entry of {str(action)!r} action "
f"on user {str(strike_user)!r}"
)

logger.debug("Printing 5 most recent audit logs:")
debug_audit_log_entry: discord.AuditLogEntry
async for debug_audit_log_entry in main_guild.audit_logs(limit=5):
logger.debug(debug_audit_log_entry)

raise NoAuditLogsStrikeTrackingError(IRRETRIEVABLE_AUDIT_LOG_MESSAGE) from None

if not audit_log_entry.user:
Expand All @@ -499,9 +493,17 @@ async def _confirm_manual_add_strike(self, strike_user: discord.User | discord.M
if applied_action_user == self.bot.user:
return

confirmation_message_channel: discord.DMChannel | discord.TextChannel = (
await self.get_confirmation_message_channel(applied_action_user)
)
fetch_log_channel_error: RuntimeError
try:
confirmation_message_channel: discord.DMChannel | discord.TextChannel = (
await self.get_confirmation_message_channel(applied_action_user)
if applied_action_user != strike_user
else await self.bot.fetch_log_channel()
)
except RuntimeError as fetch_log_channel_error:
raise StrikeTrackingError(
str(fetch_log_channel_error),
) from fetch_log_channel_error

MODERATION_ACTIONS: Final[Mapping[discord.AuditLogAction, str]] = {
discord.AuditLogAction.member_update: "timed-out",
Expand All @@ -525,7 +527,7 @@ async def _confirm_manual_add_strike(self, strike_user: discord.User | discord.M
content=(
f"""Hi {
applied_action_user.display_name
if not applied_action_user.bot
if not applied_action_user.bot and applied_action_user != strike_user
else committee_role.mention
}, """
f"""I just noticed that {
Expand Down Expand Up @@ -614,7 +616,7 @@ async def _confirm_manual_add_strike(self, strike_user: discord.User | discord.M
content=(
f"""Hi {
applied_action_user.display_name
if not applied_action_user.bot
if not applied_action_user.bot and applied_action_user != strike_user
else committee_role.mention
}, """
f"""I just noticed that {
Expand Down Expand Up @@ -701,21 +703,18 @@ async def on_member_update(self, before: discord.Member, after: discord.Member)

audit_log_entry: discord.AuditLogEntry
async for audit_log_entry in main_guild.audit_logs(limit=5):
logger.debug("Checking audit log entry: %s", str(audit_log_entry))
FOUND_CORRECT_AUDIT_LOG_ENTRY: bool = (
audit_log_entry.target == after
audit_log_entry.target.id == after.id
and audit_log_entry.action == (
discord.AuditLogAction.auto_moderation_user_communication_disabled
)
)
if FOUND_CORRECT_AUDIT_LOG_ENTRY:
logger.debug("Found it!")
await self._confirm_manual_add_strike(
strike_user=after,
action=audit_log_entry.action,
)
return
logger.debug("Above audit log entry did not match...")

# noinspection PyArgumentList
await self._confirm_manual_add_strike(
Expand Down
32 changes: 32 additions & 0 deletions utils/tex_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
from logging import Logger
from typing import TYPE_CHECKING, Final

import aiohttp
import discord
from discord import Webhook

from config import settings
from exceptions import (
Expand Down Expand Up @@ -483,3 +485,33 @@ async def get_member_from_str_id(self, str_member_id: str) -> discord.Member:
raise ValueError from user_not_in_main_guild_error

return member

async def fetch_log_channel(self) -> discord.TextChannel:
"""
Retrieve the Discord log channel.
If no DISCORD_LOG_CHANNEL_WEBHOOK_URL is specified,
a ValueError exception will be raised.
"""
if not settings["DISCORD_LOG_CHANNEL_WEBHOOK_URL"]:
NO_LOG_CHANNEL_MESSAGE: Final[str] = (
"Cannot fetch log channel, "
"when no DISCORD_LOG_CHANNEL_WEBHOOK_URL has been set."
)
raise ValueError(NO_LOG_CHANNEL_MESSAGE)
session: aiohttp.ClientSession
with aiohttp.ClientSession() as session: # type: ignore[assignment]
partial_webhook: Webhook = Webhook.from_url(
settings["DISCORD_LOG_CHANNEL_WEBHOOK_URL"],
session=session,
)

full_webhook: Webhook = await partial_webhook.fetch()
if not full_webhook.channel:
full_webhook = await self.fetch_webhook(partial_webhook.id)

if not full_webhook.channel:
LOG_CHANNEL_NOT_FOUND_MESSAGE: Final[str] = "Failed to fetch log channel."
raise RuntimeError(LOG_CHANNEL_NOT_FOUND_MESSAGE)

return full_webhook.channel

0 comments on commit 11830f7

Please sign in to comment.