aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Boris Muratov <[email protected]>2021-08-22 23:56:04 +0300
committerGravatar GitHub <[email protected]>2021-08-22 23:56:04 +0300
commitf202742a98d8e1fe82a8f84316838685ca6fcb07 (patch)
treeb4a507b55c01b549a75d5da1c8dd97d111d26f4f
parentUpdate outdated comment (diff)
parentMerge pull request #1743 from python-discord/dawnofmidnight/site-urls (diff)
Merge branch 'main' into remove-redundant-converters
-rw-r--r--bot/exts/events/__init__.py0
-rw-r--r--bot/exts/events/code_jams/__init__.py8
-rw-r--r--bot/exts/events/code_jams/_channels.py113
-rw-r--r--bot/exts/events/code_jams/_cog.py235
-rw-r--r--bot/exts/filters/antimalware.py2
-rw-r--r--bot/exts/filters/antispam.py2
-rw-r--r--bot/exts/filters/filtering.py2
-rw-r--r--bot/exts/filters/webhook_remover.py23
-rw-r--r--bot/exts/fun/duck_pond.py8
-rw-r--r--bot/exts/help_channels/_cog.py14
-rw-r--r--bot/exts/help_channels/_message.py8
-rw-r--r--bot/exts/info/code_snippets.py103
-rw-r--r--bot/exts/info/codeblock/_cog.py17
-rw-r--r--bot/exts/info/information.py26
-rw-r--r--bot/exts/info/python_news.py10
-rw-r--r--bot/exts/info/site.py14
-rw-r--r--bot/exts/moderation/incidents.py24
-rw-r--r--bot/exts/recruitment/talentpool/_review.py22
-rw-r--r--bot/exts/utils/jams.py176
-rw-r--r--bot/exts/utils/reminders.py39
-rw-r--r--bot/resources/tags/modmail.md2
-rw-r--r--tests/bot/exts/events/__init__.py0
-rw-r--r--tests/bot/exts/events/test_code_jams.py (renamed from tests/bot/exts/utils/test_jams.py)66
23 files changed, 574 insertions, 340 deletions
diff --git a/bot/exts/events/__init__.py b/bot/exts/events/__init__.py
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/bot/exts/events/__init__.py
diff --git a/bot/exts/events/code_jams/__init__.py b/bot/exts/events/code_jams/__init__.py
new file mode 100644
index 000000000..16e81e365
--- /dev/null
+++ b/bot/exts/events/code_jams/__init__.py
@@ -0,0 +1,8 @@
+from bot.bot import Bot
+
+
+def setup(bot: Bot) -> None:
+ """Load the CodeJams cog."""
+ from bot.exts.events.code_jams._cog import CodeJams
+
+ bot.add_cog(CodeJams(bot))
diff --git a/bot/exts/events/code_jams/_channels.py b/bot/exts/events/code_jams/_channels.py
new file mode 100644
index 000000000..34ff0ad41
--- /dev/null
+++ b/bot/exts/events/code_jams/_channels.py
@@ -0,0 +1,113 @@
+import logging
+import typing as t
+
+import discord
+
+from bot.constants import Categories, Channels, Roles
+
+log = logging.getLogger(__name__)
+
+MAX_CHANNELS = 50
+CATEGORY_NAME = "Code Jam"
+
+
+async def _get_category(guild: discord.Guild) -> discord.CategoryChannel:
+ """
+ Return a code jam category.
+
+ If all categories are full or none exist, create a new category.
+ """
+ for category in guild.categories:
+ if category.name == CATEGORY_NAME and len(category.channels) < MAX_CHANNELS:
+ return category
+
+ return await _create_category(guild)
+
+
+async def _create_category(guild: discord.Guild) -> discord.CategoryChannel:
+ """Create a new code jam category and return it."""
+ log.info("Creating a new code jam category.")
+
+ category_overwrites = {
+ guild.default_role: discord.PermissionOverwrite(read_messages=False),
+ guild.me: discord.PermissionOverwrite(read_messages=True)
+ }
+
+ category = await guild.create_category_channel(
+ CATEGORY_NAME,
+ overwrites=category_overwrites,
+ reason="It's code jam time!"
+ )
+
+ await _send_status_update(
+ guild, f"Created a new category with the ID {category.id} for this Code Jam's team channels."
+ )
+
+ return category
+
+
+def _get_overwrites(
+ members: list[tuple[discord.Member, bool]],
+ guild: discord.Guild,
+) -> dict[t.Union[discord.Member, discord.Role], discord.PermissionOverwrite]:
+ """Get code jam team channels permission overwrites."""
+ team_channel_overwrites = {
+ guild.default_role: discord.PermissionOverwrite(read_messages=False),
+ guild.get_role(Roles.code_jam_event_team): discord.PermissionOverwrite(read_messages=True)
+ }
+
+ for member, _ in members:
+ team_channel_overwrites[member] = discord.PermissionOverwrite(
+ read_messages=True
+ )
+
+ return team_channel_overwrites
+
+
+async def create_team_channel(
+ guild: discord.Guild,
+ team_name: str,
+ members: list[tuple[discord.Member, bool]],
+ team_leaders: discord.Role
+) -> None:
+ """Create the team's text channel."""
+ await _add_team_leader_roles(members, team_leaders)
+
+ # Get permission overwrites and category
+ team_channel_overwrites = _get_overwrites(members, guild)
+ code_jam_category = await _get_category(guild)
+
+ # Create a text channel for the team
+ await code_jam_category.create_text_channel(
+ team_name,
+ overwrites=team_channel_overwrites,
+ )
+
+
+async def create_team_leader_channel(guild: discord.Guild, team_leaders: discord.Role) -> None:
+ """Create the Team Leader Chat channel for the Code Jam team leaders."""
+ category: discord.CategoryChannel = guild.get_channel(Categories.summer_code_jam)
+
+ team_leaders_chat = await category.create_text_channel(
+ name="team-leaders-chat",
+ overwrites={
+ guild.default_role: discord.PermissionOverwrite(read_messages=False),
+ team_leaders: discord.PermissionOverwrite(read_messages=True)
+ }
+ )
+
+ await _send_status_update(guild, f"Created {team_leaders_chat.mention} in the {category} category.")
+
+
+async def _send_status_update(guild: discord.Guild, message: str) -> None:
+ """Inform the events lead with a status update when the command is ran."""
+ channel: discord.TextChannel = guild.get_channel(Channels.code_jam_planning)
+
+ await channel.send(f"<@&{Roles.events_lead}>\n\n{message}")
+
+
+async def _add_team_leader_roles(members: list[tuple[discord.Member, bool]], team_leaders: discord.Role) -> None:
+ """Assign the team leader role to the team leaders."""
+ for member, is_leader in members:
+ if is_leader:
+ await member.add_roles(team_leaders)
diff --git a/bot/exts/events/code_jams/_cog.py b/bot/exts/events/code_jams/_cog.py
new file mode 100644
index 000000000..e099f7dfa
--- /dev/null
+++ b/bot/exts/events/code_jams/_cog.py
@@ -0,0 +1,235 @@
+import asyncio
+import csv
+import logging
+import typing as t
+from collections import defaultdict
+
+import discord
+from discord import Colour, Embed, Guild, Member
+from discord.ext import commands
+
+from bot.bot import Bot
+from bot.constants import Emojis, Roles
+from bot.exts.events.code_jams import _channels
+from bot.utils.services import send_to_paste_service
+
+log = logging.getLogger(__name__)
+
+TEAM_LEADERS_COLOUR = 0x11806a
+DELETION_REACTION = "\U0001f4a5"
+
+
+class CodeJams(commands.Cog):
+ """Manages the code-jam related parts of our server."""
+
+ def __init__(self, bot: Bot):
+ self.bot = bot
+
+ @commands.group(aliases=("cj", "jam"))
+ @commands.has_any_role(Roles.admins)
+ async def codejam(self, ctx: commands.Context) -> None:
+ """A Group of commands for managing Code Jams."""
+ if ctx.invoked_subcommand is None:
+ await ctx.send_help(ctx.command)
+
+ @codejam.command()
+ async def create(self, ctx: commands.Context, csv_file: t.Optional[str] = None) -> None:
+ """
+ Create code-jam teams from a CSV file or a link to one, specifying the team names, leaders and members.
+
+ The CSV file must have 3 columns: 'Team Name', 'Team Member Discord ID', and 'Team Leader'.
+
+ This will create the text channels for the teams, and give the team leaders their roles.
+ """
+ async with ctx.typing():
+ if csv_file:
+ async with self.bot.http_session.get(csv_file) as response:
+ if response.status != 200:
+ await ctx.send(f"Got a bad response from the URL: {response.status}")
+ return
+
+ csv_file = await response.text()
+
+ elif ctx.message.attachments:
+ csv_file = (await ctx.message.attachments[0].read()).decode("utf8")
+ else:
+ raise commands.BadArgument("You must include either a CSV file or a link to one.")
+
+ teams = defaultdict(list)
+ reader = csv.DictReader(csv_file.splitlines())
+
+ for row in reader:
+ member = ctx.guild.get_member(int(row["Team Member Discord ID"]))
+
+ if member is None:
+ log.trace(f"Got an invalid member ID: {row['Team Member Discord ID']}")
+ continue
+
+ teams[row["Team Name"]].append((member, row["Team Leader"].upper() == "Y"))
+
+ team_leaders = await ctx.guild.create_role(name="Code Jam Team Leaders", colour=TEAM_LEADERS_COLOUR)
+
+ for team_name, members in teams.items():
+ await _channels.create_team_channel(ctx.guild, team_name, members, team_leaders)
+
+ await _channels.create_team_leader_channel(ctx.guild, team_leaders)
+ await ctx.send(f"{Emojis.check_mark} Created Code Jam with {len(teams)} teams.")
+
+ @codejam.command()
+ @commands.has_any_role(Roles.admins)
+ async def end(self, ctx: commands.Context) -> None:
+ """
+ Delete all code jam channels.
+
+ A confirmation message is displayed with the categories and channels to be deleted.. Pressing the added reaction
+ deletes those channels.
+ """
+ def predicate_deletion_emoji_reaction(reaction: discord.Reaction, user: discord.User) -> bool:
+ """Return True if the reaction :boom: was added by the context message author on this message."""
+ return (
+ reaction.message.id == message.id
+ and user.id == ctx.author.id
+ and str(reaction) == DELETION_REACTION
+ )
+
+ # A copy of the list of channels is stored. This is to make sure that we delete precisely the channels displayed
+ # in the confirmation message.
+ categories = self.jam_categories(ctx.guild)
+ category_channels = {category: category.channels.copy() for category in categories}
+
+ confirmation_message = await self._build_confirmation_message(category_channels)
+ message = await ctx.send(confirmation_message)
+ await message.add_reaction(DELETION_REACTION)
+ try:
+ await self.bot.wait_for(
+ 'reaction_add',
+ check=predicate_deletion_emoji_reaction,
+ timeout=10
+ )
+
+ except asyncio.TimeoutError:
+ await message.clear_reaction(DELETION_REACTION)
+ await ctx.send("Command timed out.", reference=message)
+ return
+
+ else:
+ await message.clear_reaction(DELETION_REACTION)
+ for category, channels in category_channels.items():
+ for channel in channels:
+ await channel.delete(reason="Code jam ended.")
+ await category.delete(reason="Code jam ended.")
+
+ await message.add_reaction(Emojis.check_mark)
+
+ @staticmethod
+ async def _build_confirmation_message(
+ categories: dict[discord.CategoryChannel, list[discord.abc.GuildChannel]]
+ ) -> str:
+ """Sends details of the channels to be deleted to the pasting service, and formats the confirmation message."""
+ def channel_repr(channel: discord.abc.GuildChannel) -> str:
+ """Formats the channel name and ID and a readable format."""
+ return f"{channel.name} ({channel.id})"
+
+ def format_category_info(category: discord.CategoryChannel, channels: list[discord.abc.GuildChannel]) -> str:
+ """Displays the category and the channels within it in a readable format."""
+ return f"{channel_repr(category)}:\n" + "\n".join(" - " + channel_repr(channel) for channel in channels)
+
+ deletion_details = "\n\n".join(
+ format_category_info(category, channels) for category, channels in categories.items()
+ )
+
+ url = await send_to_paste_service(deletion_details)
+ if url is None:
+ url = "**Unable to send deletion details to the pasting service.**"
+
+ return f"Are you sure you want to delete all code jam channels?\n\nThe channels to be deleted: {url}"
+
+ @codejam.command()
+ @commands.has_any_role(Roles.admins, Roles.code_jam_event_team)
+ async def info(self, ctx: commands.Context, member: Member) -> None:
+ """
+ Send an info embed about the member with the team they're in.
+
+ The team is found by searching the permissions of the team channels.
+ """
+ channel = self.team_channel(ctx.guild, member)
+ if not channel:
+ await ctx.send(":x: I can't find the team channel for this member.")
+ return
+
+ embed = Embed(
+ title=str(member),
+ colour=Colour.blurple()
+ )
+ embed.add_field(name="Team", value=self.team_name(channel), inline=True)
+
+ await ctx.send(embed=embed)
+
+ @codejam.command()
+ @commands.has_any_role(Roles.admins)
+ async def move(self, ctx: commands.Context, member: Member, new_team_name: str) -> None:
+ """Move participant from one team to another by changing the user's permissions for the relevant channels."""
+ old_team_channel = self.team_channel(ctx.guild, member)
+ if not old_team_channel:
+ await ctx.send(":x: I can't find the team channel for this member.")
+ return
+
+ if old_team_channel.name == new_team_name or self.team_name(old_team_channel) == new_team_name:
+ await ctx.send(f"`{member}` is already in `{new_team_name}`.")
+ return
+
+ new_team_channel = self.team_channel(ctx.guild, new_team_name)
+ if not new_team_channel:
+ await ctx.send(f":x: I can't find a team channel named `{new_team_name}`.")
+ return
+
+ await old_team_channel.set_permissions(member, overwrite=None, reason=f"Participant moved to {new_team_name}")
+ await new_team_channel.set_permissions(
+ member,
+ overwrite=discord.PermissionOverwrite(read_messages=True),
+ reason=f"Participant moved from {old_team_channel.name}"
+ )
+
+ await ctx.send(
+ f"Participant moved from `{self.team_name(old_team_channel)}` to `{self.team_name(new_team_channel)}`."
+ )
+
+ @codejam.command()
+ @commands.has_any_role(Roles.admins)
+ async def remove(self, ctx: commands.Context, member: Member) -> None:
+ """Remove the participant from their team. Does not remove the participants or leader roles."""
+ channel = self.team_channel(ctx.guild, member)
+ if not channel:
+ await ctx.send(":x: I can't find the team channel for this member.")
+ return
+
+ await channel.set_permissions(
+ member,
+ overwrite=None,
+ reason=f"Participant removed from the team {self.team_name(channel)}."
+ )
+ await ctx.send(f"Removed the participant from `{self.team_name(channel)}`.")
+
+ @staticmethod
+ def jam_categories(guild: Guild) -> list[discord.CategoryChannel]:
+ """Get all the code jam team categories."""
+ return [category for category in guild.categories if category.name == _channels.CATEGORY_NAME]
+
+ @staticmethod
+ def team_channel(guild: Guild, criterion: t.Union[str, Member]) -> t.Optional[discord.TextChannel]:
+ """Get a team channel through either a participant or the team name."""
+ for category in CodeJams.jam_categories(guild):
+ for channel in category.channels:
+ if isinstance(channel, discord.TextChannel):
+ if (
+ # If it's a string.
+ criterion == channel.name or criterion == CodeJams.team_name(channel)
+ # If it's a member.
+ or criterion in channel.overwrites
+ ):
+ return channel
+
+ @staticmethod
+ def team_name(channel: discord.TextChannel) -> str:
+ """Retrieves the team name from the given channel."""
+ return channel.name.replace("-", " ").title()
diff --git a/bot/exts/filters/antimalware.py b/bot/exts/filters/antimalware.py
index 4c4836c88..0eedeb0fb 100644
--- a/bot/exts/filters/antimalware.py
+++ b/bot/exts/filters/antimalware.py
@@ -7,7 +7,7 @@ from discord.ext.commands import Cog
from bot.bot import Bot
from bot.constants import Channels, Filter, URLs
-from bot.exts.utils.jams import CATEGORY_NAME as JAM_CATEGORY_NAME
+from bot.exts.events.code_jams._channels import CATEGORY_NAME as JAM_CATEGORY_NAME
log = logging.getLogger(__name__)
diff --git a/bot/exts/filters/antispam.py b/bot/exts/filters/antispam.py
index 3f891b2c6..226da2790 100644
--- a/bot/exts/filters/antispam.py
+++ b/bot/exts/filters/antispam.py
@@ -17,8 +17,8 @@ from bot.constants import (
Guild as GuildConfig, Icons,
)
from bot.converters import Duration
+from bot.exts.events.code_jams._channels import CATEGORY_NAME as JAM_CATEGORY_NAME
from bot.exts.moderation.modlog import ModLog
-from bot.exts.utils.jams import CATEGORY_NAME as JAM_CATEGORY_NAME
from bot.utils import lock, scheduling
from bot.utils.messages import format_user, send_attachments
diff --git a/bot/exts/filters/filtering.py b/bot/exts/filters/filtering.py
index 16aaf11cf..10cc7885d 100644
--- a/bot/exts/filters/filtering.py
+++ b/bot/exts/filters/filtering.py
@@ -19,8 +19,8 @@ from bot.constants import (
Channels, Colours, Filter,
Guild, Icons, URLs
)
+from bot.exts.events.code_jams._channels import CATEGORY_NAME as JAM_CATEGORY_NAME
from bot.exts.moderation.modlog import ModLog
-from bot.exts.utils.jams import CATEGORY_NAME as JAM_CATEGORY_NAME
from bot.utils.messages import format_user
from bot.utils.regex import INVITE_RE
from bot.utils.scheduling import Scheduler
diff --git a/bot/exts/filters/webhook_remover.py b/bot/exts/filters/webhook_remover.py
index f11fc8912..25e267426 100644
--- a/bot/exts/filters/webhook_remover.py
+++ b/bot/exts/filters/webhook_remover.py
@@ -9,12 +9,15 @@ from bot.constants import Channels, Colours, Event, Icons
from bot.exts.moderation.modlog import ModLog
from bot.utils.messages import format_user
-WEBHOOK_URL_RE = re.compile(r"((?:https?://)?discord(?:app)?\.com/api/webhooks/\d+/)\S+/?", re.IGNORECASE)
+WEBHOOK_URL_RE = re.compile(
+ r"((?:https?:\/\/)?(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/webhooks\/\d+\/)\S+\/?",
+ re.IGNORECASE
+)
ALERT_MESSAGE_TEMPLATE = (
"{user}, looks like you posted a Discord webhook URL. Therefore, your "
- "message has been removed. Your webhook may have been **compromised** so "
- "please re-create the webhook **immediately**. If you believe this was a "
+ "message has been removed, and your webhook has been deleted. "
+ "You can re-create it if you wish to. If you believe this was a "
"mistake, please let us know."
)
@@ -32,7 +35,7 @@ class WebhookRemover(Cog):
"""Get current instance of `ModLog`."""
return self.bot.get_cog("ModLog")
- async def delete_and_respond(self, msg: Message, redacted_url: str) -> None:
+ async def delete_and_respond(self, msg: Message, redacted_url: str, *, webhook_deleted: bool) -> None:
"""Delete `msg` and send a warning that it contained the Discord webhook `redacted_url`."""
# Don't log this, due internal delete, not by user. Will make different entry.
self.mod_log.ignore(Event.message_delete, msg.id)
@@ -44,9 +47,12 @@ class WebhookRemover(Cog):
return
await msg.channel.send(ALERT_MESSAGE_TEMPLATE.format(user=msg.author.mention))
-
+ if webhook_deleted:
+ delete_state = "The webhook was successfully deleted."
+ else:
+ delete_state = "There was an error when deleting the webhook, it might have already been removed."
message = (
- f"{format_user(msg.author)} posted a Discord webhook URL to {msg.channel.mention}. "
+ f"{format_user(msg.author)} posted a Discord webhook URL to {msg.channel.mention}. {delete_state} "
f"Webhook URL was `{redacted_url}`"
)
log.debug(message)
@@ -72,7 +78,10 @@ class WebhookRemover(Cog):
matches = WEBHOOK_URL_RE.search(msg.content)
if matches:
- await self.delete_and_respond(msg, matches[1] + "xxx")
+ async with self.bot.http_session.delete(matches[0]) as resp:
+ # The Discord API Returns a 204 NO CONTENT response on success.
+ deleted_successfully = resp.status == 204
+ await self.delete_and_respond(msg, matches[1] + "xxx", webhook_deleted=deleted_successfully)
@Cog.listener()
async def on_message_edit(self, before: Message, after: Message) -> None:
diff --git a/bot/exts/fun/duck_pond.py b/bot/exts/fun/duck_pond.py
index 0ac985139..7f7e4585c 100644
--- a/bot/exts/fun/duck_pond.py
+++ b/bot/exts/fun/duck_pond.py
@@ -172,8 +172,14 @@ class DuckPond(Cog):
if not self.is_helper_viewable(channel):
return
- message = await channel.fetch_message(payload.message_id)
+ try:
+ message = await channel.fetch_message(payload.message_id)
+ except discord.NotFound:
+ return # Message was deleted.
+
member = discord.utils.get(message.guild.members, id=payload.user_id)
+ if not member:
+ return # Member left or wasn't in the cache.
# Was the message sent by a human staff member?
if not self.is_staff(message.author) or message.author.bot:
diff --git a/bot/exts/help_channels/_cog.py b/bot/exts/help_channels/_cog.py
index afaf9b0bd..cfc9cf477 100644
--- a/bot/exts/help_channels/_cog.py
+++ b/bot/exts/help_channels/_cog.py
@@ -267,6 +267,8 @@ class HelpChannels(commands.Cog):
for channel in channels[:abs(missing)]:
await self.unclaim_channel(channel, closed_on=_channel.ClosingReason.CLEANUP)
+ self.available_help_channels = set(_channel.get_category_channels(self.available_category))
+
# Getting channels that need to be included in the dynamic message.
await self.update_available_help_channels()
log.trace("Dynamic available help message updated.")
@@ -387,13 +389,10 @@ class HelpChannels(commands.Cog):
)
log.trace(f"Sending dormant message for #{channel} ({channel.id}).")
- dormant_category = await channel_utils.try_get_channel(constants.Categories.help_dormant)
- available_category = await channel_utils.try_get_channel(constants.Categories.help_available)
embed = discord.Embed(
description=_message.DORMANT_MSG.format(
- dormant=dormant_category.name,
- available=available_category.name,
- asking_guide=_message.ASKING_GUIDE_URL
+ dormant=self.dormant_category.name,
+ available=self.available_category.name,
)
)
await channel.send(embed=embed)
@@ -519,11 +518,6 @@ class HelpChannels(commands.Cog):
async def update_available_help_channels(self) -> None:
"""Updates the dynamic message within #how-to-get-help for available help channels."""
- if not self.available_help_channels:
- self.available_help_channels = set(
- c for c in self.available_category.channels if not _channel.is_excluded_channel(c)
- )
-
available_channels = AVAILABLE_HELP_CHANNELS.format(
available=", ".join(
c.mention for c in sorted(self.available_help_channels, key=attrgetter("position"))
diff --git a/bot/exts/help_channels/_message.py b/bot/exts/help_channels/_message.py
index cf070be83..077b20b47 100644
--- a/bot/exts/help_channels/_message.py
+++ b/bot/exts/help_channels/_message.py
@@ -29,15 +29,15 @@ AVAILABLE_TITLE = "Available help channel"
AVAILABLE_FOOTER = "Closes after a period of inactivity, or when you send !close."
-DORMANT_MSG = """
-This help channel has been marked as **dormant**, and has been moved into the **{dormant}** \
+DORMANT_MSG = f"""
+This help channel has been marked as **dormant**, and has been moved into the **{{dormant}}** \
category at the bottom of the channel list. It is no longer possible to send messages in this \
channel until it becomes available again.
If your question wasn't answered yet, you can claim a new help channel from the \
-**{available}** category by simply asking your question again. Consider rephrasing the \
+**{{available}}** category by simply asking your question again. Consider rephrasing the \
question to maximize your chance of getting a good answer. If you're not sure how, have a look \
-through our guide for **[asking a good question]({asking_guide})**.
+through our guide for **[asking a good question]({ASKING_GUIDE_URL})**.
"""
diff --git a/bot/exts/info/code_snippets.py b/bot/exts/info/code_snippets.py
index 24a9ae28a..4a90a0668 100644
--- a/bot/exts/info/code_snippets.py
+++ b/bot/exts/info/code_snippets.py
@@ -4,8 +4,8 @@ import textwrap
from typing import Any
from urllib.parse import quote_plus
+import discord
from aiohttp import ClientResponseError
-from discord import Message
from discord.ext.commands import Cog
from bot.bot import Bot
@@ -45,6 +45,17 @@ class CodeSnippets(Cog):
Matches each message against a regex and prints the contents of all matched snippets.
"""
+ def __init__(self, bot: Bot):
+ """Initializes the cog's bot."""
+ self.bot = bot
+
+ self.pattern_handlers = [
+ (GITHUB_RE, self._fetch_github_snippet),
+ (GITHUB_GIST_RE, self._fetch_github_gist_snippet),
+ (GITLAB_RE, self._fetch_gitlab_snippet),
+ (BITBUCKET_RE, self._fetch_bitbucket_snippet)
+ ]
+
async def _fetch_response(self, url: str, response_format: str, **kwargs) -> Any:
"""Makes http requests using aiohttp."""
async with self.bot.http_session.get(url, raise_for_status=True, **kwargs) as response:
@@ -208,56 +219,56 @@ class CodeSnippets(Cog):
# Returns an empty codeblock if the snippet is empty
return f'{ret}``` ```'
- def __init__(self, bot: Bot):
- """Initializes the cog's bot."""
- self.bot = bot
+ async def _parse_snippets(self, content: str) -> str:
+ """Parse message content and return a string with a code block for each URL found."""
+ all_snippets = []
+
+ for pattern, handler in self.pattern_handlers:
+ for match in pattern.finditer(content):
+ try:
+ snippet = await handler(**match.groupdict())
+ all_snippets.append((match.start(), snippet))
+ except ClientResponseError as error:
+ error_message = error.message # noqa: B306
+ log.log(
+ logging.DEBUG if error.status == 404 else logging.ERROR,
+ f'Failed to fetch code snippet from {match[0]!r}: {error.status} '
+ f'{error_message} for GET {error.request_info.real_url.human_repr()}'
+ )
- self.pattern_handlers = [
- (GITHUB_RE, self._fetch_github_snippet),
- (GITHUB_GIST_RE, self._fetch_github_gist_snippet),
- (GITLAB_RE, self._fetch_gitlab_snippet),
- (BITBUCKET_RE, self._fetch_bitbucket_snippet)
- ]
+ # Sorts the list of snippets by their match index and joins them into a single message
+ return '\n'.join(map(lambda x: x[1], sorted(all_snippets)))
@Cog.listener()
- async def on_message(self, message: Message) -> None:
+ async def on_message(self, message: discord.Message) -> None:
"""Checks if the message has a snippet link, removes the embed, then sends the snippet contents."""
- if not message.author.bot:
- all_snippets = []
-
- for pattern, handler in self.pattern_handlers:
- for match in pattern.finditer(message.content):
- try:
- snippet = await handler(**match.groupdict())
- all_snippets.append((match.start(), snippet))
- except ClientResponseError as error:
- error_message = error.message # noqa: B306
- log.log(
- logging.DEBUG if error.status == 404 else logging.ERROR,
- f'Failed to fetch code snippet from {match[0]!r}: {error.status} '
- f'{error_message} for GET {error.request_info.real_url.human_repr()}'
- )
-
- # Sorts the list of snippets by their match index and joins them into a single message
- message_to_send = '\n'.join(map(lambda x: x[1], sorted(all_snippets)))
-
- if 0 < len(message_to_send) <= 2000 and message_to_send.count('\n') <= 15:
+ if message.author.bot:
+ return
+
+ message_to_send = await self._parse_snippets(message.content)
+ destination = message.channel
+
+ if 0 < len(message_to_send) <= 2000 and message_to_send.count('\n') <= 15:
+ try:
await message.edit(suppress=True)
- if len(message_to_send) > 1000 and message.channel.id != Channels.bot_commands:
- # Redirects to #bot-commands if the snippet contents are too long
- await self.bot.wait_until_guild_available()
- await message.channel.send(('The snippet you tried to send was too long. Please '
- f'see <#{Channels.bot_commands}> for the full snippet.'))
- bot_commands_channel = self.bot.get_channel(Channels.bot_commands)
- await wait_for_deletion(
- await bot_commands_channel.send(message_to_send),
- (message.author.id,)
- )
- else:
- await wait_for_deletion(
- await message.channel.send(message_to_send),
- (message.author.id,)
- )
+ except discord.NotFound:
+ # Don't send snippets if the original message was deleted.
+ return
+
+ if len(message_to_send) > 1000 and message.channel.id != Channels.bot_commands:
+ # Redirects to #bot-commands if the snippet contents are too long
+ await self.bot.wait_until_guild_available()
+ destination = self.bot.get_channel(Channels.bot_commands)
+
+ await message.channel.send(
+ 'The snippet you tried to send was too long. '
+ f'Please see {destination.mention} for the full snippet.'
+ )
+
+ await wait_for_deletion(
+ await destination.send(message_to_send),
+ (message.author.id,)
+ )
def setup(bot: Bot) -> None:
diff --git a/bot/exts/info/codeblock/_cog.py b/bot/exts/info/codeblock/_cog.py
index 9094d9d15..9a0705d2b 100644
--- a/bot/exts/info/codeblock/_cog.py
+++ b/bot/exts/info/codeblock/_cog.py
@@ -177,10 +177,13 @@ class CodeBlockCog(Cog, name="Code Block"):
if not bot_message:
return
- if not instructions:
- log.info("User's incorrect code block has been fixed. Removing instructions message.")
- await bot_message.delete()
- del self.codeblock_message_ids[payload.message_id]
- else:
- log.info("Message edited but still has invalid code blocks; editing the instructions.")
- await bot_message.edit(embed=self.create_embed(instructions))
+ try:
+ if not instructions:
+ log.info("User's incorrect code block was fixed. Removing instructions message.")
+ await bot_message.delete()
+ del self.codeblock_message_ids[payload.message_id]
+ else:
+ log.info("Message edited but still has invalid code blocks; editing instructions.")
+ await bot_message.edit(embed=self.create_embed(instructions))
+ except discord.NotFound:
+ log.debug("Could not find instructions message; it was probably deleted.")
diff --git a/bot/exts/info/information.py b/bot/exts/info/information.py
index ff3fb9408..a9ea403f7 100644
--- a/bot/exts/info/information.py
+++ b/bot/exts/info/information.py
@@ -186,21 +186,21 @@ class Information(Cog):
online_presences = py_invite.approximate_presence_count
offline_presences = py_invite.approximate_member_count - online_presences
member_status = (
- f"{constants.Emojis.status_online} {online_presences} "
- f"{constants.Emojis.status_offline} {offline_presences}"
+ f"{constants.Emojis.status_online} {online_presences:,} "
+ f"{constants.Emojis.status_offline} {offline_presences:,}"
)
- embed.description = textwrap.dedent(f"""
- Created: {created}
- Voice region: {region}\
- {features}
- Roles: {num_roles}
- Member status: {member_status}
- """)
+ embed.description = (
+ f"Created: {created}"
+ f"\nVoice region: {region}"
+ f"{features}"
+ f"\nRoles: {num_roles}"
+ f"\nMember status: {member_status}"
+ )
embed.set_thumbnail(url=ctx.guild.icon_url)
# Members
- total_members = ctx.guild.member_count
+ total_members = f"{ctx.guild.member_count:,}"
member_counts = self.get_member_counts(ctx.guild)
member_info = "\n".join(f"{role}: {count}" for role, count in member_counts.items())
embed.add_field(name=f"Members: {total_members}", value=member_info)
@@ -257,7 +257,11 @@ class Information(Cog):
badges.append(emoji)
if on_server:
- joined = discord_timestamp(user.joined_at, TimestampFormats.RELATIVE)
+ if user.joined_at:
+ joined = discord_timestamp(user.joined_at, TimestampFormats.RELATIVE)
+ else:
+ joined = "Unable to get join date"
+
# The 0 is for excluding the default @everyone role,
# and the -1 is for reversing the order of the roles to highest to lowest in hierarchy.
roles = ", ".join(role.mention for role in user.roles[:0:-1])
diff --git a/bot/exts/info/python_news.py b/bot/exts/info/python_news.py
index a7837c93a..63eb4ac17 100644
--- a/bot/exts/info/python_news.py
+++ b/bot/exts/info/python_news.py
@@ -1,4 +1,5 @@
import logging
+import re
import typing as t
from datetime import date, datetime
@@ -72,6 +73,11 @@ class PythonNews(Cog):
if mail["name"].split("@")[0] in constants.PythonNews.mail_lists:
self.webhook_names[mail["name"].split("@")[0]] = mail["display_name"]
+ @staticmethod
+ def escape_markdown(content: str) -> str:
+ """Escape the markdown underlines and spoilers."""
+ return re.sub(r"[_|]", lambda match: "\\" + match[0], content)
+
async def post_pep_news(self) -> None:
"""Fetch new PEPs and when they don't have announcement in #python-news, create it."""
# Wait until everything is ready and http_session available
@@ -103,7 +109,7 @@ class PythonNews(Cog):
# Build an embed and send a webhook
embed = discord.Embed(
title=new["title"],
- description=new["summary"],
+ description=self.escape_markdown(new["summary"]),
timestamp=new_datetime,
url=new["link"],
colour=constants.Colours.soft_green
@@ -167,7 +173,7 @@ class PythonNews(Cog):
):
continue
- content = email_information["content"]
+ content = self.escape_markdown(email_information["content"])
link = THREAD_URL.format(id=thread["href"].split("/")[-2], list=maillist)
# Build an embed and send a message to the webhook
diff --git a/bot/exts/info/site.py b/bot/exts/info/site.py
index fb5b99086..28eb558a6 100644
--- a/bot/exts/info/site.py
+++ b/bot/exts/info/site.py
@@ -9,7 +9,7 @@ from bot.pagination import LinePaginator
log = logging.getLogger(__name__)
-PAGES_URL = f"{URLs.site_schema}{URLs.site}/pages"
+BASE_URL = f"{URLs.site_schema}{URLs.site}"
class Site(Cog):
@@ -43,7 +43,7 @@ class Site(Cog):
@site_group.command(name="resources", root_aliases=("resources", "resource"))
async def site_resources(self, ctx: Context) -> None:
"""Info about the site's Resources page."""
- learning_url = f"{PAGES_URL}/resources"
+ learning_url = f"{BASE_URL}/resources"
embed = Embed(title="Resources")
embed.set_footer(text=f"{learning_url}")
@@ -59,7 +59,7 @@ class Site(Cog):
@site_group.command(name="tools", root_aliases=("tools",))
async def site_tools(self, ctx: Context) -> None:
"""Info about the site's Tools page."""
- tools_url = f"{PAGES_URL}/resources/tools"
+ tools_url = f"{BASE_URL}/resources/tools"
embed = Embed(title="Tools")
embed.set_footer(text=f"{tools_url}")
@@ -74,7 +74,7 @@ class Site(Cog):
@site_group.command(name="help")
async def site_help(self, ctx: Context) -> None:
"""Info about the site's Getting Help page."""
- url = f"{PAGES_URL}/resources/guides/asking-good-questions"
+ url = f"{BASE_URL}/pages/guides/pydis-guides/asking-good-questions/"
embed = Embed(title="Asking Good Questions")
embed.set_footer(text=url)
@@ -90,7 +90,7 @@ class Site(Cog):
@site_group.command(name="faq", root_aliases=("faq",))
async def site_faq(self, ctx: Context) -> None:
"""Info about the site's FAQ page."""
- url = f"{PAGES_URL}/frequently-asked-questions"
+ url = f"{BASE_URL}/pages/frequently-asked-questions"
embed = Embed(title="FAQ")
embed.set_footer(text=url)
@@ -107,13 +107,13 @@ class Site(Cog):
@site_group.command(name="rules", aliases=("r", "rule"), root_aliases=("rules", "rule"))
async def site_rules(self, ctx: Context, rules: Greedy[int]) -> None:
"""Provides a link to all rules or, if specified, displays specific rule(s)."""
- rules_embed = Embed(title='Rules', color=Colour.blurple(), url=f'{PAGES_URL}/rules')
+ rules_embed = Embed(title='Rules', color=Colour.blurple(), url=f'{BASE_URL}/pages/rules')
if not rules:
# Rules were not submitted. Return the default description.
rules_embed.description = (
"The rules and guidelines that apply to this community can be found on"
- f" our [rules page]({PAGES_URL}/rules). We expect"
+ f" our [rules page]({BASE_URL}/pages/rules). We expect"
" all members of the community to have read and understood these."
)
diff --git a/bot/exts/moderation/incidents.py b/bot/exts/moderation/incidents.py
index 0e479d33f..561e0251e 100644
--- a/bot/exts/moderation/incidents.py
+++ b/bot/exts/moderation/incidents.py
@@ -143,7 +143,14 @@ async def add_signals(incident: discord.Message) -> None:
log.trace(f"Skipping emoji as it's already been placed: {signal_emoji}")
else:
log.trace(f"Adding reaction: {signal_emoji}")
- await incident.add_reaction(signal_emoji.value)
+ try:
+ await incident.add_reaction(signal_emoji.value)
+ except discord.NotFound as e:
+ if e.code != 10008:
+ raise
+
+ log.trace(f"Couldn't react with signal because message {incident.id} was deleted; skipping incident")
+ return
class Incidents(Cog):
@@ -288,14 +295,20 @@ class Incidents(Cog):
members_roles: t.Set[int] = {role.id for role in member.roles}
if not members_roles & ALLOWED_ROLES: # Intersection is truthy on at least 1 common element
log.debug(f"Removing invalid reaction: user {member} is not permitted to send signals")
- await incident.remove_reaction(reaction, member)
+ try:
+ await incident.remove_reaction(reaction, member)
+ except discord.NotFound:
+ log.trace("Couldn't remove reaction because the reaction or its message was deleted")
return
try:
signal = Signal(reaction)
except ValueError:
log.debug(f"Removing invalid reaction: emoji {reaction} is not a valid signal")
- await incident.remove_reaction(reaction, member)
+ try:
+ await incident.remove_reaction(reaction, member)
+ except discord.NotFound:
+ log.trace("Couldn't remove reaction because the reaction or its message was deleted")
return
log.trace(f"Received signal: {signal}")
@@ -313,7 +326,10 @@ class Incidents(Cog):
confirmation_task = self.make_confirmation_task(incident, timeout)
log.trace("Deleting original message")
- await incident.delete()
+ try:
+ await incident.delete()
+ except discord.NotFound:
+ log.trace("Couldn't delete message because it was already deleted")
log.trace(f"Awaiting deletion confirmation: {timeout=} seconds")
try:
diff --git a/bot/exts/recruitment/talentpool/_review.py b/bot/exts/recruitment/talentpool/_review.py
index 3a1e66970..4d496a1f7 100644
--- a/bot/exts/recruitment/talentpool/_review.py
+++ b/bot/exts/recruitment/talentpool/_review.py
@@ -15,7 +15,7 @@ from discord.ext.commands import Context
from bot.api import ResponseCodeError
from bot.bot import Bot
-from bot.constants import Channels, Colours, Emojis, Guild, Roles
+from bot.constants import Channels, Colours, Emojis, Guild
from bot.utils.messages import count_unique_users_reaction, pin_no_system_message
from bot.utils.scheduling import Scheduler
from bot.utils.time import get_time_delta, time_since
@@ -33,10 +33,12 @@ MAX_MESSAGE_SIZE = 2000
# Maximum amount of characters allowed in an embed
MAX_EMBED_SIZE = 4000
-# Regex finding the user ID of a user mention
-MENTION_RE = re.compile(r"<@!?(\d+?)>")
-# Regex matching role pings
-ROLE_MENTION_RE = re.compile(r"<@&\d+>")
+# Regex for finding the first message of a nomination, and extracting the nominee.
+# Historic nominations will have 2 role mentions at the start, new ones won't, optionally match for this.
+NOMINATION_MESSAGE_REGEX = re.compile(
+ r"(?:<@&\d+> <@&\d+>\n)*?<@!?(\d+?)> \(.+#\d{4}\) for Helper!\n\n\*\*Nominated by:\*\*",
+ re.MULTILINE
+)
class Reviewer:
@@ -118,7 +120,7 @@ class Reviewer:
f"I tried to review the user with ID `{user_id}`, but they don't appear to be on the server :pensive:"
), None
- opening = f"<@&{Roles.mod_team}> <@&{Roles.admins}>\n{member.mention} ({member}) for Helper!"
+ opening = f"{member.mention} ({member}) for Helper!"
current_nominations = "\n\n".join(
f"**<@{entry['actor']}>:** {entry['reason'] or '*no reason given*'}"
@@ -142,14 +144,14 @@ class Reviewer:
"""Archive this vote to #nomination-archive."""
message = await message.fetch()
- # We consider the first message in the nomination to contain the two role pings
+ # We consider the first message in the nomination to contain the user ping, username#discrim, and fixed text
messages = [message]
- if not len(ROLE_MENTION_RE.findall(message.content)) >= 2:
+ if not NOMINATION_MESSAGE_REGEX.search(message.content):
with contextlib.suppress(NoMoreItems):
async for new_message in message.channel.history(before=message.created_at):
messages.append(new_message)
- if len(ROLE_MENTION_RE.findall(new_message.content)) >= 2:
+ if NOMINATION_MESSAGE_REGEX.search(new_message.content):
break
log.debug(f"Found {len(messages)} messages: {', '.join(str(m.id) for m in messages)}")
@@ -161,7 +163,7 @@ class Reviewer:
content = "".join(parts)
# We assume that the first user mentioned is the user that we are voting on
- user_id = int(MENTION_RE.search(content).group(1))
+ user_id = int(NOMINATION_MESSAGE_REGEX.search(content).group(1))
# Get reaction counts
reviewed = await count_unique_users_reaction(
diff --git a/bot/exts/utils/jams.py b/bot/exts/utils/jams.py
deleted file mode 100644
index 87ae847f6..000000000
--- a/bot/exts/utils/jams.py
+++ /dev/null
@@ -1,176 +0,0 @@
-import csv
-import logging
-import typing as t
-from collections import defaultdict
-
-import discord
-from discord.ext import commands
-
-from bot.bot import Bot
-from bot.constants import Categories, Channels, Emojis, Roles
-
-log = logging.getLogger(__name__)
-
-MAX_CHANNELS = 50
-CATEGORY_NAME = "Code Jam"
-TEAM_LEADERS_COLOUR = 0x11806a
-
-
-class CodeJams(commands.Cog):
- """Manages the code-jam related parts of our server."""
-
- def __init__(self, bot: Bot):
- self.bot = bot
-
- @commands.group()
- @commands.has_any_role(Roles.admins)
- async def codejam(self, ctx: commands.Context) -> None:
- """A Group of commands for managing Code Jams."""
- if ctx.invoked_subcommand is None:
- await ctx.send_help(ctx.command)
-
- @codejam.command()
- async def create(self, ctx: commands.Context, csv_file: t.Optional[str]) -> None:
- """
- Create code-jam teams from a CSV file or a link to one, specifying the team names, leaders and members.
-
- The CSV file must have 3 columns: 'Team Name', 'Team Member Discord ID', and 'Team Leader'.
-
- This will create the text channels for the teams, and give the team leaders their roles.
- """
- async with ctx.typing():
- if csv_file:
- async with self.bot.http_session.get(csv_file) as response:
- if response.status != 200:
- await ctx.send(f"Got a bad response from the URL: {response.status}")
- return
-
- csv_file = await response.text()
-
- elif ctx.message.attachments:
- csv_file = (await ctx.message.attachments[0].read()).decode("utf8")
- else:
- raise commands.BadArgument("You must include either a CSV file or a link to one.")
-
- teams = defaultdict(list)
- reader = csv.DictReader(csv_file.splitlines())
-
- for row in reader:
- member = ctx.guild.get_member(int(row["Team Member Discord ID"]))
-
- if member is None:
- log.trace(f"Got an invalid member ID: {row['Team Member Discord ID']}")
- continue
-
- teams[row["Team Name"]].append((member, row["Team Leader"].upper() == "Y"))
-
- team_leaders = await ctx.guild.create_role(name="Code Jam Team Leaders", colour=TEAM_LEADERS_COLOUR)
-
- for team_name, members in teams.items():
- await self.create_team_channel(ctx.guild, team_name, members, team_leaders)
-
- await self.create_team_leader_channel(ctx.guild, team_leaders)
- await ctx.send(f"{Emojis.check_mark} Created Code Jam with {len(teams)} teams.")
-
- async def get_category(self, guild: discord.Guild) -> discord.CategoryChannel:
- """
- Return a code jam category.
-
- If all categories are full or none exist, create a new category.
- """
- for category in guild.categories:
- if category.name == CATEGORY_NAME and len(category.channels) < MAX_CHANNELS:
- return category
-
- return await self.create_category(guild)
-
- async def create_category(self, guild: discord.Guild) -> discord.CategoryChannel:
- """Create a new code jam category and return it."""
- log.info("Creating a new code jam category.")
-
- category_overwrites = {
- guild.default_role: discord.PermissionOverwrite(read_messages=False),
- guild.me: discord.PermissionOverwrite(read_messages=True)
- }
-
- category = await guild.create_category_channel(
- CATEGORY_NAME,
- overwrites=category_overwrites,
- reason="It's code jam time!"
- )
-
- await self.send_status_update(
- guild, f"Created a new category with the ID {category.id} for this Code Jam's team channels."
- )
-
- return category
-
- @staticmethod
- def get_overwrites(
- members: list[tuple[discord.Member, bool]],
- guild: discord.Guild,
- ) -> dict[t.Union[discord.Member, discord.Role], discord.PermissionOverwrite]:
- """Get code jam team channels permission overwrites."""
- team_channel_overwrites = {
- guild.default_role: discord.PermissionOverwrite(read_messages=False),
- guild.get_role(Roles.code_jam_event_team): discord.PermissionOverwrite(read_messages=True)
- }
-
- for member, _ in members:
- team_channel_overwrites[member] = discord.PermissionOverwrite(
- read_messages=True
- )
-
- return team_channel_overwrites
-
- async def create_team_channel(
- self,
- guild: discord.Guild,
- team_name: str,
- members: list[tuple[discord.Member, bool]],
- team_leaders: discord.Role
- ) -> None:
- """Create the team's text channel."""
- await self.add_team_leader_roles(members, team_leaders)
-
- # Get permission overwrites and category
- team_channel_overwrites = self.get_overwrites(members, guild)
- code_jam_category = await self.get_category(guild)
-
- # Create a text channel for the team
- await code_jam_category.create_text_channel(
- team_name,
- overwrites=team_channel_overwrites,
- )
-
- async def create_team_leader_channel(self, guild: discord.Guild, team_leaders: discord.Role) -> None:
- """Create the Team Leader Chat channel for the Code Jam team leaders."""
- category: discord.CategoryChannel = guild.get_channel(Categories.summer_code_jam)
-
- team_leaders_chat = await category.create_text_channel(
- name="team-leaders-chat",
- overwrites={
- guild.default_role: discord.PermissionOverwrite(read_messages=False),
- team_leaders: discord.PermissionOverwrite(read_messages=True)
- }
- )
-
- await self.send_status_update(guild, f"Created {team_leaders_chat.mention} in the {category} category.")
-
- async def send_status_update(self, guild: discord.Guild, message: str) -> None:
- """Inform the events lead with a status update when the command is ran."""
- channel: discord.TextChannel = guild.get_channel(Channels.code_jam_planning)
-
- await channel.send(f"<@&{Roles.events_lead}>\n\n{message}")
-
- @staticmethod
- async def add_team_leader_roles(members: list[tuple[discord.Member, bool]], team_leaders: discord.Role) -> None:
- """Assign team leader role, the jammer role and their team role."""
- for member, is_leader in members:
- if is_leader:
- await member.add_roles(team_leaders)
-
-
-def setup(bot: Bot) -> None:
- """Load the CodeJams cog."""
- bot.add_cog(CodeJams(bot))
diff --git a/bot/exts/utils/reminders.py b/bot/exts/utils/reminders.py
index 7b8c5c4b3..cc13f6ebe 100644
--- a/bot/exts/utils/reminders.py
+++ b/bot/exts/utils/reminders.py
@@ -18,7 +18,7 @@ from bot.utils.checks import has_any_role_check, has_no_roles_check
from bot.utils.lock import lock_arg
from bot.utils.messages import send_denial
from bot.utils.scheduling import Scheduler
-from bot.utils.time import TimestampFormats, discord_timestamp, time_since
+from bot.utils.time import TimestampFormats, discord_timestamp
log = logging.getLogger(__name__)
@@ -172,32 +172,39 @@ class Reminders(Cog):
if not is_valid:
# No need to cancel the task too; it'll simply be done once this coroutine returns.
return
-
embed = discord.Embed()
- embed.colour = discord.Colour.blurple()
- embed.set_author(
- icon_url=Icons.remind_blurple,
- name="It has arrived!"
- )
-
- # Let's not use a codeblock to keep emojis and mentions working. Embeds are safe anyway.
- embed.description = f"Here's your reminder: {reminder['content']}."
-
- if reminder.get("jump_url"): # keep backward compatibility
- embed.description += f"\n[Jump back to when you created the reminder]({reminder['jump_url']})"
-
if expected_time:
embed.colour = discord.Colour.red()
embed.set_author(
icon_url=Icons.remind_red,
- name=f"Sorry it should have arrived {time_since(expected_time)} !"
+ name="Sorry, your reminder should have arrived earlier!"
+ )
+ else:
+ embed.colour = discord.Colour.blurple()
+ embed.set_author(
+ icon_url=Icons.remind_blurple,
+ name="It has arrived!"
)
+ # Let's not use a codeblock to keep emojis and mentions working. Embeds are safe anyway.
+ embed.description = f"Here's your reminder: {reminder['content']}"
+
+ # Here the jump URL is in the format of base_url/guild_id/channel_id/message_id
additional_mentions = ' '.join(
mentionable.mention for mentionable in self.get_mentionables(reminder["mentions"])
)
- await channel.send(content=f"{user.mention} {additional_mentions}", embed=embed)
+ jump_url = reminder.get("jump_url")
+ embed.description += f"\n[Jump back to when you created the reminder]({jump_url})"
+ partial_message = channel.get_partial_message(int(jump_url.split("/")[-1]))
+ try:
+ await partial_message.reply(content=f"{additional_mentions}", embed=embed)
+ except discord.HTTPException as e:
+ log.info(
+ f"There was an error when trying to reply to a reminder invocation message, {e}, "
+ "fall back to using jump_url"
+ )
+ await channel.send(content=f"{user.mention} {additional_mentions}", embed=embed)
log.debug(f"Deleting reminder #{reminder['id']} (the user has been reminded).")
await self.bot.api_client.delete(f"bot/reminders/{reminder['id']}")
diff --git a/bot/resources/tags/modmail.md b/bot/resources/tags/modmail.md
index 412468174..8ac19c8a7 100644
--- a/bot/resources/tags/modmail.md
+++ b/bot/resources/tags/modmail.md
@@ -6,4 +6,4 @@ It supports attachments, codeblocks, and reactions. As communication happens ove
**To use it, simply send a direct message to the bot.**
-Should there be an urgent and immediate need for a moderator or admin to look at a channel, feel free to ping the <@&831776746206265384> or <@&267628507062992896> role instead.
+Should there be an urgent and immediate need for a moderator to look at a channel, feel free to ping the <@&831776746206265384> role instead.
diff --git a/tests/bot/exts/events/__init__.py b/tests/bot/exts/events/__init__.py
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/bot/exts/events/__init__.py
diff --git a/tests/bot/exts/utils/test_jams.py b/tests/bot/exts/events/test_code_jams.py
index 368a15476..b9ee1e363 100644
--- a/tests/bot/exts/utils/test_jams.py
+++ b/tests/bot/exts/events/test_code_jams.py
@@ -1,14 +1,15 @@
import unittest
-from unittest.mock import AsyncMock, MagicMock, create_autospec
+from unittest.mock import AsyncMock, MagicMock, create_autospec, patch
from discord import CategoryChannel
from discord.ext.commands import BadArgument
from bot.constants import Roles
-from bot.exts.utils import jams
+from bot.exts.events import code_jams
+from bot.exts.events.code_jams import _channels, _cog
from tests.helpers import (
MockAttachment, MockBot, MockCategoryChannel, MockContext,
- MockGuild, MockMember, MockRole, MockTextChannel
+ MockGuild, MockMember, MockRole, MockTextChannel, autospec
)
TEST_CSV = b"""\
@@ -40,7 +41,7 @@ class JamCodejamCreateTests(unittest.IsolatedAsyncioTestCase):
self.command_user = MockMember([self.admin_role])
self.guild = MockGuild([self.admin_role])
self.ctx = MockContext(bot=self.bot, author=self.command_user, guild=self.guild)
- self.cog = jams.CodeJams(self.bot)
+ self.cog = _cog.CodeJams(self.bot)
async def test_message_without_attachments(self):
"""If no link or attachments are provided, commands.BadArgument should be raised."""
@@ -49,7 +50,9 @@ class JamCodejamCreateTests(unittest.IsolatedAsyncioTestCase):
with self.assertRaises(BadArgument):
await self.cog.create(self.cog, self.ctx, None)
- async def test_result_sending(self):
+ @patch.object(_channels, "create_team_channel")
+ @patch.object(_channels, "create_team_leader_channel")
+ async def test_result_sending(self, create_leader_channel, create_team_channel):
"""Should call `ctx.send` when everything goes right."""
self.ctx.message.attachments = [MockAttachment()]
self.ctx.message.attachments[0].read = AsyncMock()
@@ -61,14 +64,12 @@ class JamCodejamCreateTests(unittest.IsolatedAsyncioTestCase):
self.ctx.guild.create_role = AsyncMock()
self.ctx.guild.create_role.return_value = team_leaders
- self.cog.create_team_channel = AsyncMock()
- self.cog.create_team_leader_channel = AsyncMock()
self.cog.add_roles = AsyncMock()
await self.cog.create(self.cog, self.ctx, None)
- self.cog.create_team_channel.assert_awaited()
- self.cog.create_team_leader_channel.assert_awaited_once_with(
+ create_team_channel.assert_awaited()
+ create_leader_channel.assert_awaited_once_with(
self.ctx.guild, team_leaders
)
self.ctx.send.assert_awaited_once()
@@ -81,25 +82,24 @@ class JamCodejamCreateTests(unittest.IsolatedAsyncioTestCase):
self.ctx.send.assert_awaited_once()
- async def test_category_doesnt_exist(self):
+ @patch.object(_channels, "_send_status_update")
+ async def test_category_doesnt_exist(self, update):
"""Should create a new code jam category."""
subtests = (
[],
- [get_mock_category(jams.MAX_CHANNELS, jams.CATEGORY_NAME)],
- [get_mock_category(jams.MAX_CHANNELS - 2, "other")],
+ [get_mock_category(_channels.MAX_CHANNELS, _channels.CATEGORY_NAME)],
+ [get_mock_category(_channels.MAX_CHANNELS - 2, "other")],
)
- self.cog.send_status_update = AsyncMock()
-
for categories in subtests:
- self.cog.send_status_update.reset_mock()
+ update.reset_mock()
self.guild.reset_mock()
self.guild.categories = categories
with self.subTest(categories=categories):
- actual_category = await self.cog.get_category(self.guild)
+ actual_category = await _channels._get_category(self.guild)
- self.cog.send_status_update.assert_called_once()
+ update.assert_called_once()
self.guild.create_category_channel.assert_awaited_once()
category_overwrites = self.guild.create_category_channel.call_args[1]["overwrites"]
@@ -109,45 +109,41 @@ class JamCodejamCreateTests(unittest.IsolatedAsyncioTestCase):
async def test_category_channel_exist(self):
"""Should not try to create category channel."""
- expected_category = get_mock_category(jams.MAX_CHANNELS - 2, jams.CATEGORY_NAME)
+ expected_category = get_mock_category(_channels.MAX_CHANNELS - 2, _channels.CATEGORY_NAME)
self.guild.categories = [
- get_mock_category(jams.MAX_CHANNELS - 2, "other"),
+ get_mock_category(_channels.MAX_CHANNELS - 2, "other"),
expected_category,
- get_mock_category(0, jams.CATEGORY_NAME),
+ get_mock_category(0, _channels.CATEGORY_NAME),
]
- actual_category = await self.cog.get_category(self.guild)
+ actual_category = await _channels._get_category(self.guild)
self.assertEqual(expected_category, actual_category)
async def test_channel_overwrites(self):
"""Should have correct permission overwrites for users and roles."""
leader = (MockMember(), True)
members = [leader] + [(MockMember(), False) for _ in range(4)]
- overwrites = self.cog.get_overwrites(members, self.guild)
+ overwrites = _channels._get_overwrites(members, self.guild)
for member, _ in members:
self.assertTrue(overwrites[member].read_messages)
- async def test_team_channels_creation(self):
+ @patch.object(_channels, "_get_overwrites")
+ @patch.object(_channels, "_get_category")
+ @autospec(_channels, "_add_team_leader_roles", pass_mocks=False)
+ async def test_team_channels_creation(self, get_category, get_overwrites):
"""Should create a text channel for a team."""
team_leaders = MockRole()
members = [(MockMember(), True)] + [(MockMember(), False) for _ in range(5)]
category = MockCategoryChannel()
category.create_text_channel = AsyncMock()
- self.cog.get_overwrites = MagicMock()
- self.cog.get_category = AsyncMock()
- self.cog.get_category.return_value = category
- self.cog.add_team_leader_roles = AsyncMock()
-
- await self.cog.create_team_channel(self.guild, "my-team", members, team_leaders)
- self.cog.add_team_leader_roles.assert_awaited_once_with(members, team_leaders)
- self.cog.get_overwrites.assert_called_once_with(members, self.guild)
- self.cog.get_category.assert_awaited_once_with(self.guild)
+ get_category.return_value = category
+ await _channels.create_team_channel(self.guild, "my-team", members, team_leaders)
category.create_text_channel.assert_awaited_once_with(
"my-team",
- overwrites=self.cog.get_overwrites.return_value
+ overwrites=get_overwrites.return_value
)
async def test_jam_roles_adding(self):
@@ -156,7 +152,7 @@ class JamCodejamCreateTests(unittest.IsolatedAsyncioTestCase):
leader = MockMember()
members = [(leader, True)] + [(MockMember(), False) for _ in range(4)]
- await self.cog.add_team_leader_roles(members, leader_role)
+ await _channels._add_team_leader_roles(members, leader_role)
leader.add_roles.assert_awaited_once_with(leader_role)
for member, is_leader in members:
@@ -170,5 +166,5 @@ class CodeJamSetup(unittest.TestCase):
def test_setup(self):
"""Should call `bot.add_cog`."""
bot = MockBot()
- jams.setup(bot)
+ code_jams.setup(bot)
bot.add_cog.assert_called_once()