From 4775b174597e72100641b97ea6ef2c9e63622d60 Mon Sep 17 00:00:00 2001 From: Slushie Date: Wed, 8 Jul 2020 21:28:17 +0100 Subject: Edit BadArgument error message --- bot/cogs/error_handler.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/cogs/error_handler.py b/bot/cogs/error_handler.py index 5de961116..a7f8074e2 100644 --- a/bot/cogs/error_handler.py +++ b/bot/cogs/error_handler.py @@ -170,7 +170,7 @@ class ErrorHandler(Cog): await prepared_help_command self.bot.stats.incr("errors.too_many_arguments") elif isinstance(e, errors.BadArgument): - await ctx.send(f"Bad argument: {e}\n") + await ctx.send("Bad argument: Please double check your input arguments and try again.\n") await prepared_help_command self.bot.stats.incr("errors.bad_argument") elif isinstance(e, errors.BadUnionArgument): -- cgit v1.2.3 From 9060c909f6816eb2fff97a41d709a1c67b034af1 Mon Sep 17 00:00:00 2001 From: Slushie Date: Wed, 8 Jul 2020 21:29:14 +0100 Subject: Create a filtering function to filter eval results --- bot/cogs/filtering.py | 172 +++++++++++++++++++++++++++++++++++--------------- 1 file changed, 120 insertions(+), 52 deletions(-) diff --git a/bot/cogs/filtering.py b/bot/cogs/filtering.py index 76ea68660..ae77ad7f0 100644 --- a/bot/cogs/filtering.py +++ b/bot/cogs/filtering.py @@ -2,7 +2,7 @@ import asyncio import logging import re from datetime import datetime, timedelta -from typing import List, Mapping, Optional, Union +from typing import List, Mapping, Optional, Tuple, Union import dateutil import discord.errors @@ -200,24 +200,66 @@ class Filtering(Cog, Scheduler): # Update time when alert sent await self.name_alerts.set(member.id, datetime.utcnow().timestamp()) + async def _filter_eval(self, result: str, msg: Message) -> bool: + """ + Filter the result of an !eval to see if it violates any of our rules, and then respond accordingly. + + Also requires the original message, to check whether to filter and for mod logs. + Returns whether a filter was triggered or not. + """ + # Should we filter this message? + if self._check_filter(msg): + for filter_name, _filter in self.filters.items(): + # Is this specific filter enabled in the config? + # We also do not need to worry about filters that take the full message, + # since all we have is an arbitrary string. + if _filter["enabled"] and _filter["content_only"]: + match = await _filter["function"](result) + + if match: + # If this is a filter (not a watchlist), we set the variable so we know + # that it has been triggered + if _filter["type"] == "filter": + filter_triggered = True + + # We do not have to check against DM channels since !eval cannot be used there. + channel_str = f"in {msg.channel.mention}" + + message_content, additional_embeds, additional_embeds_msg = self._add_stats( + filter_name, match, result + ) + + message = ( + f"The {filter_name} {_filter['type']} was triggered " + f"by **{msg.author}** " + f"(`{msg.author.id}`) {channel_str} using !eval with " + f"[the following message]({msg.jump_url}):\n\n" + f"{message_content}" + ) + + log.debug(message) + + # Send pretty mod log embed to mod-alerts + await self.mod_log.send_log_message( + icon_url=Icons.filtering, + colour=Colour(Colours.soft_red), + title=f"{_filter['type'].title()} triggered!", + text=message, + thumbnail=msg.author.avatar_url_as(static_format="png"), + channel_id=Channels.mod_alerts, + ping_everyone=Filter.ping_everyone, + additional_embeds=additional_embeds, + additional_embeds_msg=additional_embeds_msg + ) + + break # We don't want multiple filters to trigger + + return filter_triggered + async def _filter_message(self, msg: Message, delta: Optional[int] = None) -> None: """Filter the input message to see if it violates any of our rules, and then respond accordingly.""" # Should we filter this message? - role_whitelisted = False - - if type(msg.author) is Member: # Only Member has roles, not User. - for role in msg.author.roles: - if role.id in Filter.role_whitelist: - role_whitelisted = True - - filter_message = ( - msg.channel.id not in Filter.channel_whitelist # Channel not in whitelist - and not role_whitelisted # Role not in whitelist - and not msg.author.bot # Author not a bot - ) - - # If none of the above, we can start filtering. - if filter_message: + if self._check_filter(msg): for filter_name, _filter in self.filters.items(): # Is this specific filter enabled in the config? if _filter["enabled"]: @@ -276,16 +318,9 @@ class Filtering(Cog, Scheduler): else: channel_str = f"in {msg.channel.mention}" - # Word and match stats for watch_regex - if filter_name == "watch_regex": - surroundings = match.string[max(match.start() - 10, 0): match.end() + 10] - message_content = ( - f"**Match:** '{match[0]}'\n" - f"**Location:** '...{escape_markdown(surroundings)}...'\n" - f"\n**Original Message:**\n{escape_markdown(msg.content)}" - ) - else: # Use content of discord Message - message_content = msg.content + message_content, additional_embeds, additional_embeds_msg = self._add_stats( + filter_name, match, msg.content + ) message = ( f"The {filter_name} {_filter['type']} was triggered " @@ -297,30 +332,6 @@ class Filtering(Cog, Scheduler): log.debug(message) - self.bot.stats.incr(f"filters.{filter_name}") - - additional_embeds = None - additional_embeds_msg = None - - # The function returns True for invalid invites. - # They have no data so additional embeds can't be created for them. - if filter_name == "filter_invites" and match is not True: - additional_embeds = [] - for invite, data in match.items(): - embed = discord.Embed(description=( - f"**Members:**\n{data['members']}\n" - f"**Active:**\n{data['active']}" - )) - embed.set_author(name=data["name"]) - embed.set_thumbnail(url=data["icon"]) - embed.set_footer(text=f"Guild Invite Code: {invite}") - additional_embeds.append(embed) - additional_embeds_msg = "For the following guild(s):" - - elif filter_name == "watch_rich_embeds": - additional_embeds = msg.embeds - additional_embeds_msg = "With the following embed(s):" - # Send pretty mod log embed to mod-alerts await self.mod_log.send_log_message( icon_url=Icons.filtering, @@ -336,6 +347,63 @@ class Filtering(Cog, Scheduler): break # We don't want multiple filters to trigger + def _add_stats(self, name: str, match: Union[re.Match, dict, bool, List[discord.Embed]], content: str) -> Tuple[ + str, Optional[List[discord.Embed]], Optional[str] + ]: + """Adds relevant statistical information to the relevant filter and increments the bot's stats.""" + # Word and match stats for watch_regex + if name == "watch_regex": + surroundings = match.string[max(match.start() - 10, 0): match.end() + 10] + message_content = ( + f"**Match:** '{match[0]}'\n" + f"**Location:** '...{escape_markdown(surroundings)}...'\n" + f"\n**Original Message:**\n{escape_markdown(content)}" + ) + else: # Use original content + message_content = content + + additional_embeds = None + additional_embeds_msg = None + + self.bot.stats.incr(f"filters.{name}") + + # The function returns True for invalid invites. + # They have no data so additional embeds can't be created for them. + if name == "filter_invites" and match is not True: + additional_embeds = [] + for invite, data in match.items(): + embed = discord.Embed(description=( + f"**Members:**\n{data['members']}\n" + f"**Active:**\n{data['active']}" + )) + embed.set_author(name=data["name"]) + embed.set_thumbnail(url=data["icon"]) + embed.set_footer(text=f"Guild Invite Code: {invite}") + additional_embeds.append(embed) + additional_embeds_msg = "For the following guild(s):" + + elif name == "watch_rich_embeds": + additional_embeds = match + additional_embeds_msg = "With the following embed(s):" + + return message_content, additional_embeds, additional_embeds_msg + + @staticmethod + def _check_filter(msg: Message) -> bool: + """Check whitelists to see if we should filter this message.""" + role_whitelisted = False + + if type(msg.author) is Member: # Only Member has roles, not User. + for role in msg.author.roles: + if role.id in Filter.role_whitelist: + role_whitelisted = True + + return ( + msg.channel.id not in Filter.channel_whitelist # Channel not in whitelist + and not role_whitelisted # Role not in whitelist + and not msg.author.bot # Author not a bot + ) + @staticmethod async def _has_watch_regex_match(text: str) -> Union[bool, re.Match]: """ @@ -428,7 +496,7 @@ class Filtering(Cog, Scheduler): return invite_data if invite_data else False @staticmethod - async def _has_rich_embed(msg: Message) -> bool: + async def _has_rich_embed(msg: Message) -> Union[bool, List[discord.Embed]]: """Determines if `msg` contains any rich embeds not auto-generated from a URL.""" if msg.embeds: for embed in msg.embeds: @@ -437,7 +505,7 @@ class Filtering(Cog, Scheduler): if not embed.url or embed.url not in urls: # If `embed.url` does not exist or if `embed.url` is not part of the content # of the message, it's unlikely to be an auto-generated embed by Discord. - return True + return msg.embeds else: log.trace( "Found a rich embed sent by a regular user account, " -- cgit v1.2.3 From 63846d17a851c97fe073e5c1e27cd65719d2c854 Mon Sep 17 00:00:00 2001 From: Slushie Date: Wed, 8 Jul 2020 21:35:04 +0100 Subject: Call the filter eval command after receiving an eval result --- bot/cogs/snekbox.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/bot/cogs/snekbox.py b/bot/cogs/snekbox.py index a2a7574d4..649bab492 100644 --- a/bot/cogs/snekbox.py +++ b/bot/cogs/snekbox.py @@ -212,7 +212,12 @@ class Snekbox(Cog): else: self.bot.stats.incr("snekbox.python.success") - response = await ctx.send(msg) + filter_cog = self.bot.get_cog("Filtering") + filter_triggered = await filter_cog._filter_eval(msg, ctx.message) + if filter_triggered: + response = await ctx.send("Attempt to circumvent filter detected. Moderator team has been alerted.") + else: + response = await ctx.send(msg) self.bot.loop.create_task( wait_for_deletion(response, user_ids=(ctx.author.id,), client=ctx.bot) ) -- cgit v1.2.3 From 5f73f40eeb025e6694443a8bc4535df894b83e4f Mon Sep 17 00:00:00 2001 From: slushiegoose <38522108+slushiegoose@users.noreply.github.com> Date: Thu, 9 Jul 2020 15:29:03 +0100 Subject: Fix missing hypen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Leon Sandøy --- bot/cogs/error_handler.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/cogs/error_handler.py b/bot/cogs/error_handler.py index a7f8074e2..233851e41 100644 --- a/bot/cogs/error_handler.py +++ b/bot/cogs/error_handler.py @@ -170,7 +170,7 @@ class ErrorHandler(Cog): await prepared_help_command self.bot.stats.incr("errors.too_many_arguments") elif isinstance(e, errors.BadArgument): - await ctx.send("Bad argument: Please double check your input arguments and try again.\n") + await ctx.send("Bad argument: Please double-check your input arguments and try again.\n") await prepared_help_command self.bot.stats.incr("errors.bad_argument") elif isinstance(e, errors.BadUnionArgument): -- cgit v1.2.3 From 288c6526e03388bf7ff5b3b1e8b861ad1a7f6e63 Mon Sep 17 00:00:00 2001 From: Slushie Date: Thu, 9 Jul 2020 15:32:27 +0100 Subject: Add missing variable assignment to stop NameErrors occurring --- bot/cogs/filtering.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bot/cogs/filtering.py b/bot/cogs/filtering.py index ae77ad7f0..4c97073c3 100644 --- a/bot/cogs/filtering.py +++ b/bot/cogs/filtering.py @@ -207,6 +207,7 @@ class Filtering(Cog, Scheduler): Also requires the original message, to check whether to filter and for mod logs. Returns whether a filter was triggered or not. """ + filter_triggered = False # Should we filter this message? if self._check_filter(msg): for filter_name, _filter in self.filters.items(): -- cgit v1.2.3 From cb5e361d04cd9c430bca4fb3496284e469d35c98 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Sun, 12 Jul 2020 14:40:26 +0200 Subject: Add the #dm_log ID to constants. https://github.com/python-discord/bot/issues/667 --- bot/constants.py | 1 + config-default.yml | 1 + 2 files changed, 2 insertions(+) diff --git a/bot/constants.py b/bot/constants.py index a1b392c82..074699025 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -416,6 +416,7 @@ class Channels(metaclass=YAMLGetter): user_log: int verification: int voice_log: int + dm_log: int class Webhooks(metaclass=YAMLGetter): diff --git a/config-default.yml b/config-default.yml index 64c4e715b..d3ba45f88 100644 --- a/config-default.yml +++ b/config-default.yml @@ -150,6 +150,7 @@ guild: mod_log: &MOD_LOG 282638479504965634 user_log: 528976905546760203 voice_log: 640292421988646961 + dm_log: 653713721625018428 # Off-topic off_topic_0: 291284109232308226 -- cgit v1.2.3 From 9042325f06523e04a2c51b39fd20436cd6eaa3fc Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Sun, 12 Jul 2020 14:57:15 +0200 Subject: Refactor Duck Pond embed sender to be a util. https://github.com/python-discord/bot/issues/667 --- bot/cogs/duck_pond.py | 30 ++++++++---------------------- bot/utils/webhooks.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 22 deletions(-) create mode 100644 bot/utils/webhooks.py diff --git a/bot/cogs/duck_pond.py b/bot/cogs/duck_pond.py index 5b6a7fd62..89b4ad0e4 100644 --- a/bot/cogs/duck_pond.py +++ b/bot/cogs/duck_pond.py @@ -1,5 +1,5 @@ import logging -from typing import Optional, Union +from typing import Union import discord from discord import Color, Embed, Member, Message, RawReactionActionEvent, User, errors @@ -7,7 +7,8 @@ from discord.ext.commands import Cog from bot import constants from bot.bot import Bot -from bot.utils.messages import send_attachments, sub_clyde +from bot.utils.messages import send_attachments +from bot.utils.webhooks import send_webhook log = logging.getLogger(__name__) @@ -18,6 +19,7 @@ class DuckPond(Cog): def __init__(self, bot: Bot): self.bot = bot self.webhook_id = constants.Webhooks.duck_pond + self.webhook = None self.bot.loop.create_task(self.fetch_webhook()) async def fetch_webhook(self) -> None: @@ -47,24 +49,6 @@ class DuckPond(Cog): return True return False - async def send_webhook( - self, - content: Optional[str] = None, - username: Optional[str] = None, - avatar_url: Optional[str] = None, - embed: Optional[Embed] = None, - ) -> None: - """Send a webhook to the duck_pond channel.""" - try: - await self.webhook.send( - content=content, - username=sub_clyde(username), - avatar_url=avatar_url, - embed=embed - ) - except discord.HTTPException: - log.exception("Failed to send a message to the Duck Pool webhook") - async def count_ducks(self, message: Message) -> int: """ Count the number of ducks in the reactions of a specific message. @@ -97,7 +81,8 @@ class DuckPond(Cog): clean_content = message.clean_content if clean_content: - await self.send_webhook( + await send_webhook( + webhook=self.webhook, content=message.clean_content, username=message.author.display_name, avatar_url=message.author.avatar_url @@ -111,7 +96,8 @@ class DuckPond(Cog): description=":x: **This message contained an attachment, but it could not be retrieved**", color=Color.red() ) - await self.send_webhook( + await send_webhook( + webhook=self.webhook, embed=e, username=message.author.display_name, avatar_url=message.author.avatar_url diff --git a/bot/utils/webhooks.py b/bot/utils/webhooks.py new file mode 100644 index 000000000..37fdfe907 --- /dev/null +++ b/bot/utils/webhooks.py @@ -0,0 +1,34 @@ +import logging +from typing import Optional + +import discord +from discord import Embed + +from bot.utils.messages import sub_clyde + +log = logging.getLogger(__name__) + + +async def send_webhook( + webhook: discord.Webhook, + content: Optional[str] = None, + username: Optional[str] = None, + avatar_url: Optional[str] = None, + embed: Optional[Embed] = None, + wait: Optional[bool] = False +) -> None: + """ + Send a message using the provided webhook. + + This uses sub_clyde() and tries for an HTTPException to ensure it doesn't crash. + """ + try: + await webhook.send( + content=content, + username=sub_clyde(username), + avatar_url=avatar_url, + embed=embed, + wait=wait, + ) + except discord.HTTPException: + log.exception("Failed to send a message to the webhook!") -- cgit v1.2.3 From ef65033eaed01a2459561dd9fe37133b595f3d3a Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Sun, 12 Jul 2020 15:10:00 +0200 Subject: Refactor python_news.py to use webhook util. https://github.com/python-discord/bot/issues/667 --- bot/cogs/python_news.py | 70 ++++++++++++++++++++----------------------------- bot/utils/webhooks.py | 4 +-- 2 files changed, 31 insertions(+), 43 deletions(-) diff --git a/bot/cogs/python_news.py b/bot/cogs/python_news.py index adefd5c7c..1d8f2aeb0 100644 --- a/bot/cogs/python_news.py +++ b/bot/cogs/python_news.py @@ -10,7 +10,7 @@ from discord.ext.tasks import loop from bot import constants from bot.bot import Bot -from bot.utils.messages import sub_clyde +from bot.utils.webhooks import send_webhook PEPS_RSS_URL = "https://www.python.org/dev/peps/peps.rss/" @@ -100,13 +100,20 @@ class PythonNews(Cog): ): continue - msg = await self.send_webhook( + # Build an embed and send a webhook + embed = discord.Embed( title=new["title"], description=new["summary"], timestamp=new_datetime, url=new["link"], - webhook_profile_name=data["feed"]["title"], - footer=data["feed"]["title"] + colour=constants.Colours.soft_green + ) + embed.set_footer(text=data["feed"]["title"], icon_url=AVATAR_URL) + msg = await send_webhook( + webhook=self.webhook, + username=data["feed"]["title"], + embed=embed, + wait=True, ) payload["data"]["pep"].append(pep_nr) @@ -161,15 +168,28 @@ class PythonNews(Cog): content = email_information["content"] link = THREAD_URL.format(id=thread["href"].split("/")[-2], list=maillist) - msg = await self.send_webhook( + + # Build an embed and send a message to the webhook + embed = discord.Embed( title=thread_information["subject"], description=content[:500] + f"... [continue reading]({link})" if len(content) > 500 else content, timestamp=new_date, url=link, - author=f"{email_information['sender_name']} ({email_information['sender']['address']})", - author_url=MAILMAN_PROFILE_URL.format(id=email_information["sender"]["mailman_id"]), - webhook_profile_name=self.webhook_names[maillist], - footer=f"Posted to {self.webhook_names[maillist]}" + colour=constants.Colours.soft_green + ) + embed.set_author( + name=f"{email_information['sender_name']} ({email_information['sender']['address']})", + url=MAILMAN_PROFILE_URL.format(id=email_information["sender"]["mailman_id"]), + ) + embed.set_footer( + text=f"Posted to {self.webhook_names[maillist]}", + icon_url=AVATAR_URL, + ) + msg = await send_webhook( + webhook=self.webhook, + username=self.webhook_names[maillist], + embed=embed, + wait=True, ) payload["data"][maillist].append(thread_information["thread_id"]) @@ -182,38 +202,6 @@ class PythonNews(Cog): await self.bot.api_client.put("bot/bot-settings/news", json=payload) - async def send_webhook(self, - title: str, - description: str, - timestamp: datetime, - url: str, - webhook_profile_name: str, - footer: str, - author: t.Optional[str] = None, - author_url: t.Optional[str] = None, - ) -> discord.Message: - """Send webhook entry and return sent message.""" - embed = discord.Embed( - title=title, - description=description, - timestamp=timestamp, - url=url, - colour=constants.Colours.soft_green - ) - if author and author_url: - embed.set_author( - name=author, - url=author_url - ) - embed.set_footer(text=footer, icon_url=AVATAR_URL) - - return await self.webhook.send( - embed=embed, - username=sub_clyde(webhook_profile_name), - avatar_url=AVATAR_URL, - wait=True - ) - async def get_thread_and_first_mail(self, maillist: str, thread_identifier: str) -> t.Tuple[t.Any, t.Any]: """Get mail thread and first mail from mail.python.org based on `maillist` and `thread_identifier`.""" async with self.bot.http_session.get( diff --git a/bot/utils/webhooks.py b/bot/utils/webhooks.py index 37fdfe907..66f82ec66 100644 --- a/bot/utils/webhooks.py +++ b/bot/utils/webhooks.py @@ -16,14 +16,14 @@ async def send_webhook( avatar_url: Optional[str] = None, embed: Optional[Embed] = None, wait: Optional[bool] = False -) -> None: +) -> discord.Message: """ Send a message using the provided webhook. This uses sub_clyde() and tries for an HTTPException to ensure it doesn't crash. """ try: - await webhook.send( + return await webhook.send( content=content, username=sub_clyde(username), avatar_url=avatar_url, -- cgit v1.2.3 From 3fce243e15996eb81157c198544fcc705e46e1e6 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Sun, 12 Jul 2020 15:27:23 +0200 Subject: Relay all DMs and embeds to #dm-log. https://github.com/python-discord/bot/issues/667 --- bot/__main__.py | 1 + bot/cogs/dm_relay.py | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 bot/cogs/dm_relay.py diff --git a/bot/__main__.py b/bot/__main__.py index 37e62c2f1..49388455a 100644 --- a/bot/__main__.py +++ b/bot/__main__.py @@ -54,6 +54,7 @@ bot.load_extension("bot.cogs.verification") # Feature cogs bot.load_extension("bot.cogs.alias") bot.load_extension("bot.cogs.defcon") +bot.load_extension("bot.cogs.dm_relay") bot.load_extension("bot.cogs.duck_pond") bot.load_extension("bot.cogs.eval") bot.load_extension("bot.cogs.information") diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py new file mode 100644 index 000000000..32ac0e4ee --- /dev/null +++ b/bot/cogs/dm_relay.py @@ -0,0 +1,66 @@ +import logging + +import discord +from discord import Color +from discord.ext.commands import Cog + +from bot import constants +from bot.bot import Bot +from bot.utils.messages import send_attachments +from bot.utils.webhooks import send_webhook + +log = logging.getLogger(__name__) + + +class DMRelay(Cog): + """Debug logging module.""" + + def __init__(self, bot: Bot): + self.bot = bot + self.webhook_id = constants.Webhooks.dm_log + self.webhook = None + self.bot.loop.create_task(self.fetch_webhook()) + + async def fetch_webhook(self) -> None: + """Fetches the webhook object, so we can post to it.""" + await self.bot.wait_until_guild_available() + + try: + self.webhook = await self.bot.fetch_webhook(self.webhook_id) + except discord.HTTPException: + log.exception(f"Failed to fetch webhook with id `{self.webhook_id}`") + + @Cog.listener() + async def on_message(self, message: discord.Message) -> None: + """Relays the message's content and attachments to the dm_log channel.""" + clean_content = message.clean_content + if clean_content: + await send_webhook( + webhook=self.webhook, + content=message.clean_content, + username=message.author.display_name, + avatar_url=message.author.avatar_url + ) + + # Handle any attachments + if message.attachments: + try: + await send_attachments(message, self.webhook) + except (discord.errors.Forbidden, discord.errors.NotFound): + e = discord.Embed( + description=":x: **This message contained an attachment, but it could not be retrieved**", + color=Color.red() + ) + await send_webhook( + webhook=self.webhook, + embed=e, + username=message.author.display_name, + avatar_url=message.author.avatar_url + ) + except discord.HTTPException: + log.exception("Failed to send an attachment to the webhook") + + +def setup(bot: Bot) -> None: + """Load the DMRelay cog.""" + bot.add_cog(DMRelay(bot)) -- cgit v1.2.3 From 5007e736b93017003f02a75d12ce1ef8bae9fd69 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Sun, 12 Jul 2020 15:34:39 +0200 Subject: Replace channel ID with webhook ID for dm_log. https://github.com/python-discord/bot/issues/667 --- bot/constants.py | 2 +- config-default.yml | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/bot/constants.py b/bot/constants.py index 074699025..3f44003a8 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -416,7 +416,6 @@ class Channels(metaclass=YAMLGetter): user_log: int verification: int voice_log: int - dm_log: int class Webhooks(metaclass=YAMLGetter): @@ -428,6 +427,7 @@ class Webhooks(metaclass=YAMLGetter): reddit: int duck_pond: int dev_log: int + dm_log: int class Roles(metaclass=YAMLGetter): diff --git a/config-default.yml b/config-default.yml index d3ba45f88..c09902a5d 100644 --- a/config-default.yml +++ b/config-default.yml @@ -150,7 +150,6 @@ guild: mod_log: &MOD_LOG 282638479504965634 user_log: 528976905546760203 voice_log: 640292421988646961 - dm_log: 653713721625018428 # Off-topic off_topic_0: 291284109232308226 @@ -252,10 +251,9 @@ guild: duck_pond: 637821475327311927 dev_log: 680501655111729222 python_news: &PYNEWS_WEBHOOK 704381182279942324 - + dm_log: 654567640664244225 filter: - # What do we filter? filter_zalgo: false filter_invites: true -- cgit v1.2.3 From 4349fdedaae43f35f9821aa61c91a1e76908b0b5 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Sun, 12 Jul 2020 15:39:40 +0200 Subject: Only relay DMs, and only from humans. https://github.com/python-discord/bot/issues/667 --- bot/cogs/dm_relay.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py index 32ac0e4ee..bb060fe90 100644 --- a/bot/cogs/dm_relay.py +++ b/bot/cogs/dm_relay.py @@ -33,6 +33,10 @@ class DMRelay(Cog): @Cog.listener() async def on_message(self, message: discord.Message) -> None: """Relays the message's content and attachments to the dm_log channel.""" + # Only relay DMs from humans + if message.author.bot or message.guild: + return + clean_content = message.clean_content if clean_content: await send_webhook( -- cgit v1.2.3 From df1730ef5d51223fe1d5a2cfe8c027e5177ae9c7 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Sun, 12 Jul 2020 16:30:03 +0200 Subject: Fix DuckPond tests now that send_webhook is gone. Some of the tests were failing because they were expecting send_webhook to be a method of the DuckPond cog, other tests simply were no longer applicable, and have been removed. https://github.com/python-discord/bot/issues/667 --- tests/bot/cogs/test_duck_pond.py | 51 ++++++++++------------------------------ 1 file changed, 12 insertions(+), 39 deletions(-) diff --git a/tests/bot/cogs/test_duck_pond.py b/tests/bot/cogs/test_duck_pond.py index a8c0107c6..cfe10aebf 100644 --- a/tests/bot/cogs/test_duck_pond.py +++ b/tests/bot/cogs/test_duck_pond.py @@ -129,38 +129,6 @@ class DuckPondTests(base.LoggingTestsMixin, unittest.IsolatedAsyncioTestCase): ): self.assertEqual(expected_return, actual_return) - def test_send_webhook_correctly_passes_on_arguments(self): - """The `send_webhook` method should pass the arguments to the webhook correctly.""" - self.cog.webhook = helpers.MockAsyncWebhook() - - content = "fake content" - username = "fake username" - avatar_url = "fake avatar_url" - embed = "fake embed" - - asyncio.run(self.cog.send_webhook(content, username, avatar_url, embed)) - - self.cog.webhook.send.assert_called_once_with( - content=content, - username=username, - avatar_url=avatar_url, - embed=embed - ) - - def test_send_webhook_logs_when_sending_message_fails(self): - """The `send_webhook` method should catch a `discord.HTTPException` and log accordingly.""" - self.cog.webhook = helpers.MockAsyncWebhook() - self.cog.webhook.send.side_effect = discord.HTTPException(response=MagicMock(), message="Something failed.") - - log = logging.getLogger('bot.cogs.duck_pond') - with self.assertLogs(logger=log, level=logging.ERROR) as log_watcher: - asyncio.run(self.cog.send_webhook()) - - self.assertEqual(len(log_watcher.records), 1) - - record = log_watcher.records[0] - self.assertEqual(record.levelno, logging.ERROR) - def _get_reaction( self, emoji: typing.Union[str, helpers.MockEmoji], @@ -280,16 +248,20 @@ class DuckPondTests(base.LoggingTestsMixin, unittest.IsolatedAsyncioTestCase): async def test_relay_message_correctly_relays_content_and_attachments(self): """The `relay_message` method should correctly relay message content and attachments.""" - send_webhook_path = f"{MODULE_PATH}.DuckPond.send_webhook" + send_webhook_path = f"{MODULE_PATH}.send_webhook" send_attachments_path = f"{MODULE_PATH}.send_attachments" + author = MagicMock( + display_name="x", + avatar_url="https://" + ) self.cog.webhook = helpers.MockAsyncWebhook() test_values = ( - (helpers.MockMessage(clean_content="", attachments=[]), False, False), - (helpers.MockMessage(clean_content="message", attachments=[]), True, False), - (helpers.MockMessage(clean_content="", attachments=["attachment"]), False, True), - (helpers.MockMessage(clean_content="message", attachments=["attachment"]), True, True), + (helpers.MockMessage(author=author, clean_content="", attachments=[]), False, False), + (helpers.MockMessage(author=author, clean_content="message", attachments=[]), True, False), + (helpers.MockMessage(author=author, clean_content="", attachments=["attachment"]), False, True), + (helpers.MockMessage(author=author, clean_content="message", attachments=["attachment"]), True, True), ) for message, expect_webhook_call, expect_attachment_call in test_values: @@ -314,14 +286,14 @@ class DuckPondTests(base.LoggingTestsMixin, unittest.IsolatedAsyncioTestCase): for side_effect in side_effects: # pragma: no cover send_attachments.side_effect = side_effect - with patch(f"{MODULE_PATH}.DuckPond.send_webhook", new_callable=AsyncMock) as send_webhook: + with patch(f"{MODULE_PATH}.send_webhook", new_callable=AsyncMock) as send_webhook: with self.subTest(side_effect=type(side_effect).__name__): with self.assertNotLogs(logger=log, level=logging.ERROR): await self.cog.relay_message(message) self.assertEqual(send_webhook.call_count, 2) - @patch(f"{MODULE_PATH}.DuckPond.send_webhook", new_callable=AsyncMock) + @patch(f"{MODULE_PATH}.send_webhook", new_callable=AsyncMock) @patch(f"{MODULE_PATH}.send_attachments", new_callable=AsyncMock) async def test_relay_message_handles_attachment_http_error(self, send_attachments, send_webhook): """The `relay_message` method should handle irretrievable attachments.""" @@ -337,6 +309,7 @@ class DuckPondTests(base.LoggingTestsMixin, unittest.IsolatedAsyncioTestCase): await self.cog.relay_message(message) send_webhook.assert_called_once_with( + webhook=self.cog.webhook, content=message.clean_content, username=message.author.display_name, avatar_url=message.author.avatar_url -- cgit v1.2.3 From aaf8db7550e8b95354d6f079c99ef2beb400cac8 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Sun, 12 Jul 2020 20:19:54 +0200 Subject: Add a way to respond to DMs. This shouldn't be used as a replacement for ModMail, but I think it makes sense to have the feature just in case #dm-log provides an interesting use-case where responding as the bot makes sense. It's a bit of a curiosity, and Ves hates it, but I included it anyway. https://github.com/python-discord/bot/issues/667 --- bot/cogs/dm_relay.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py index bb060fe90..df19000fe 100644 --- a/bot/cogs/dm_relay.py +++ b/bot/cogs/dm_relay.py @@ -1,7 +1,9 @@ import logging +from typing import Optional import discord from discord import Color +from discord.ext import commands from discord.ext.commands import Cog from bot import constants @@ -20,6 +22,32 @@ class DMRelay(Cog): self.webhook_id = constants.Webhooks.dm_log self.webhook = None self.bot.loop.create_task(self.fetch_webhook()) + self.last_dm_user = None + + @commands.command(aliases=("reply",)) + async def send_dm(self, ctx: commands.Context, member: Optional[discord.Member], *, message: str) -> None: + """ + Allows you to send a DM to a user from the bot. + + If `member` is not provided, it will send to the last user who DM'd the bot. + + This feature should be used extremely sparingly. Use ModMail if you need to have a serious + conversation with a user. This is just for responding to extraordinary DMs, having a little + fun with users, and telling people they are DMing the wrong bot. + + NOTE: This feature will be removed if it is overused. + """ + if member: + await member.send(message) + await ctx.message.add_reaction("✅") + return + elif self.last_dm_user: + await self.last_dm_user.send(message) + await ctx.message.add_reaction("✅") + return + else: + log.debug("Unable to send a DM to the user.") + await ctx.message.add_reaction("❌") async def fetch_webhook(self) -> None: """Fetches the webhook object, so we can post to it.""" @@ -45,6 +73,7 @@ class DMRelay(Cog): username=message.author.display_name, avatar_url=message.author.avatar_url ) + self.last_dm_user = message.author # Handle any attachments if message.attachments: -- cgit v1.2.3 From ed2368791870bd0b464391d9da7b13de15b322a3 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Mon, 13 Jul 2020 15:13:39 +0200 Subject: Better docstring for DMRelay cog. https://github.com/python-discord/bot/issues/667 --- bot/cogs/dm_relay.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py index df19000fe..c6206629e 100644 --- a/bot/cogs/dm_relay.py +++ b/bot/cogs/dm_relay.py @@ -15,7 +15,7 @@ log = logging.getLogger(__name__) class DMRelay(Cog): - """Debug logging module.""" + """Relay direct messages to and from the bot.""" def __init__(self, bot: Bot): self.bot = bot -- cgit v1.2.3 From ab1546611a9952ddb45f211901ad129c2e8c5007 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Mon, 13 Jul 2020 15:14:31 +0200 Subject: Add avatar_url in python_news.py https://github.com/python-discord/bot/issues/667 --- bot/cogs/python_news.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/bot/cogs/python_news.py b/bot/cogs/python_news.py index 1d8f2aeb0..0ab5738a4 100644 --- a/bot/cogs/python_news.py +++ b/bot/cogs/python_news.py @@ -113,6 +113,7 @@ class PythonNews(Cog): webhook=self.webhook, username=data["feed"]["title"], embed=embed, + avatar_url=AVATAR_URL, wait=True, ) payload["data"]["pep"].append(pep_nr) @@ -189,6 +190,7 @@ class PythonNews(Cog): webhook=self.webhook, username=self.webhook_names[maillist], embed=embed, + avatar_url=AVATAR_URL, wait=True, ) payload["data"][maillist].append(thread_information["thread_id"]) -- cgit v1.2.3 From 87c2ef7610a42207b0289820458285648f5dd41e Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Mon, 13 Jul 2020 15:20:59 +0200 Subject: Only mods+ may use the commands in this cog. https://github.com/python-discord/bot/issues/667 --- bot/cogs/dm_relay.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py index c6206629e..67411f57b 100644 --- a/bot/cogs/dm_relay.py +++ b/bot/cogs/dm_relay.py @@ -8,6 +8,8 @@ from discord.ext.commands import Cog from bot import constants from bot.bot import Bot +from bot.constants import MODERATION_ROLES +from bot.utils.checks import with_role_check from bot.utils.messages import send_attachments from bot.utils.webhooks import send_webhook @@ -93,6 +95,10 @@ class DMRelay(Cog): except discord.HTTPException: log.exception("Failed to send an attachment to the webhook") + def cog_check(self, ctx: commands.Context) -> bool: + """Only allow moderators to invoke the commands in this cog.""" + return with_role_check(ctx, *MODERATION_ROLES) + def setup(bot: Bot) -> None: """Load the DMRelay cog.""" -- cgit v1.2.3 From 311936991d5543e35dbe4a5a5a13261fb44c27f4 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Mon, 13 Jul 2020 15:24:58 +0200 Subject: Don't run on_message if self.webhook is None. https://github.com/python-discord/bot/issues/667 --- bot/cogs/dm_relay.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py index 67411f57b..3d16db8a0 100644 --- a/bot/cogs/dm_relay.py +++ b/bot/cogs/dm_relay.py @@ -64,7 +64,7 @@ class DMRelay(Cog): async def on_message(self, message: discord.Message) -> None: """Relays the message's content and attachments to the dm_log channel.""" # Only relay DMs from humans - if message.author.bot or message.guild: + if message.author.bot or message.guild or self.webhook is None: return clean_content = message.clean_content -- cgit v1.2.3 From d98a67f36444a7732f4527d8c343e2fb8fad6f93 Mon Sep 17 00:00:00 2001 From: Slushie Date: Mon, 13 Jul 2020 14:25:07 +0100 Subject: rename the `_filter_eval` function to be a public function --- bot/cogs/filtering.py | 2 +- bot/cogs/snekbox.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bot/cogs/filtering.py b/bot/cogs/filtering.py index 4c97073c3..ec6769f68 100644 --- a/bot/cogs/filtering.py +++ b/bot/cogs/filtering.py @@ -200,7 +200,7 @@ class Filtering(Cog, Scheduler): # Update time when alert sent await self.name_alerts.set(member.id, datetime.utcnow().timestamp()) - async def _filter_eval(self, result: str, msg: Message) -> bool: + async def filter_eval(self, result: str, msg: Message) -> bool: """ Filter the result of an !eval to see if it violates any of our rules, and then respond accordingly. diff --git a/bot/cogs/snekbox.py b/bot/cogs/snekbox.py index 649bab492..4f73690da 100644 --- a/bot/cogs/snekbox.py +++ b/bot/cogs/snekbox.py @@ -213,7 +213,7 @@ class Snekbox(Cog): self.bot.stats.incr("snekbox.python.success") filter_cog = self.bot.get_cog("Filtering") - filter_triggered = await filter_cog._filter_eval(msg, ctx.message) + filter_triggered = await filter_cog.filter_eval(msg, ctx.message) if filter_triggered: response = await ctx.send("Attempt to circumvent filter detected. Moderator team has been alerted.") else: -- cgit v1.2.3 From aa0b20bdd780bc75cadde781981d063287bfe5ce Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Mon, 13 Jul 2020 15:27:41 +0200 Subject: Remove redundant clean_content variable. https://github.com/python-discord/bot/issues/667 --- bot/cogs/dm_relay.py | 3 +-- bot/cogs/duck_pond.py | 4 +--- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py index 3d16db8a0..494c71066 100644 --- a/bot/cogs/dm_relay.py +++ b/bot/cogs/dm_relay.py @@ -67,8 +67,7 @@ class DMRelay(Cog): if message.author.bot or message.guild or self.webhook is None: return - clean_content = message.clean_content - if clean_content: + if message.clean_content: await send_webhook( webhook=self.webhook, content=message.clean_content, diff --git a/bot/cogs/duck_pond.py b/bot/cogs/duck_pond.py index 89b4ad0e4..7021069fa 100644 --- a/bot/cogs/duck_pond.py +++ b/bot/cogs/duck_pond.py @@ -78,9 +78,7 @@ class DuckPond(Cog): async def relay_message(self, message: Message) -> None: """Relays the message's content and attachments to the duck pond channel.""" - clean_content = message.clean_content - - if clean_content: + if message.clean_content: await send_webhook( webhook=self.webhook, content=message.clean_content, -- cgit v1.2.3 From b40a5f0de6758eb9dfb79ac3f34fbc0bf90d8a1e Mon Sep 17 00:00:00 2001 From: Slushie Date: Mon, 13 Jul 2020 16:08:40 +0100 Subject: check for the filter_cog in case it is unloaded --- bot/cogs/snekbox.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/bot/cogs/snekbox.py b/bot/cogs/snekbox.py index 4f73690da..662f90869 100644 --- a/bot/cogs/snekbox.py +++ b/bot/cogs/snekbox.py @@ -213,7 +213,9 @@ class Snekbox(Cog): self.bot.stats.incr("snekbox.python.success") filter_cog = self.bot.get_cog("Filtering") - filter_triggered = await filter_cog.filter_eval(msg, ctx.message) + filter_triggered = False + if filter_cog: + filter_triggered = await filter_cog.filter_eval(msg, ctx.message) if filter_triggered: response = await ctx.send("Attempt to circumvent filter detected. Moderator team has been alerted.") else: -- cgit v1.2.3 From f1b1d0cb723abbbf7d4b49ac4b42fe0b7f266692 Mon Sep 17 00:00:00 2001 From: Slushie Date: Mon, 13 Jul 2020 16:09:08 +0100 Subject: edit snekbox tests to work with filtering --- tests/bot/cogs/test_snekbox.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/bot/cogs/test_snekbox.py b/tests/bot/cogs/test_snekbox.py index cf9adbee0..98dee7a1b 100644 --- a/tests/bot/cogs/test_snekbox.py +++ b/tests/bot/cogs/test_snekbox.py @@ -233,6 +233,10 @@ class SnekboxTests(unittest.IsolatedAsyncioTestCase): self.cog.get_status_emoji = MagicMock(return_value=':yay!:') self.cog.format_output = AsyncMock(return_value=('[No output]', None)) + mocked_filter_cog = MagicMock() + mocked_filter_cog.filter_eval = AsyncMock(return_value=False) + self.bot.get_cog.return_value = mocked_filter_cog + await self.cog.send_eval(ctx, 'MyAwesomeCode') ctx.send.assert_called_once_with( '@LemonLemonishBeard#0042 :yay!: Return code 0.\n\n```py\n[No output]\n```' @@ -254,6 +258,10 @@ class SnekboxTests(unittest.IsolatedAsyncioTestCase): self.cog.get_status_emoji = MagicMock(return_value=':yay!:') self.cog.format_output = AsyncMock(return_value=('Way too long beard', 'lookatmybeard.com')) + mocked_filter_cog = MagicMock() + mocked_filter_cog.filter_eval = AsyncMock(return_value=False) + self.bot.get_cog.return_value = mocked_filter_cog + await self.cog.send_eval(ctx, 'MyAwesomeCode') ctx.send.assert_called_once_with( '@LemonLemonishBeard#0042 :yay!: Return code 0.' @@ -275,6 +283,10 @@ class SnekboxTests(unittest.IsolatedAsyncioTestCase): self.cog.get_status_emoji = MagicMock(return_value=':nope!:') self.cog.format_output = AsyncMock() # This function isn't called + mocked_filter_cog = MagicMock() + mocked_filter_cog.filter_eval = AsyncMock(return_value=False) + self.bot.get_cog.return_value = mocked_filter_cog + await self.cog.send_eval(ctx, 'MyAwesomeCode') ctx.send.assert_called_once_with( '@LemonLemonishBeard#0042 :nope!: Return code 127.\n\n```py\nBeard got stuck in the eval\n```' -- cgit v1.2.3 From ea62b6bae85113be913101a41053c91497b23c9a Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Mon, 13 Jul 2020 21:09:41 +0200 Subject: Store last DM user in RedisCache. Also now catches the exception if a user has disabled DMs, and adds a red cross reaction. https://github.com/python-discord/bot/issues/667 --- bot/cogs/dm_relay.py | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py index 494c71066..3fce52b93 100644 --- a/bot/cogs/dm_relay.py +++ b/bot/cogs/dm_relay.py @@ -9,6 +9,7 @@ from discord.ext.commands import Cog from bot import constants from bot.bot import Bot from bot.constants import MODERATION_ROLES +from bot.utils import RedisCache from bot.utils.checks import with_role_check from bot.utils.messages import send_attachments from bot.utils.webhooks import send_webhook @@ -19,12 +20,14 @@ log = logging.getLogger(__name__) class DMRelay(Cog): """Relay direct messages to and from the bot.""" + # RedisCache[str, t.Union[discord.User.id, discord.Member.id]] + dm_cache = RedisCache() + def __init__(self, bot: Bot): self.bot = bot self.webhook_id = constants.Webhooks.dm_log self.webhook = None self.bot.loop.create_task(self.fetch_webhook()) - self.last_dm_user = None @commands.command(aliases=("reply",)) async def send_dm(self, ctx: commands.Context, member: Optional[discord.Member], *, message: str) -> None: @@ -39,16 +42,23 @@ class DMRelay(Cog): NOTE: This feature will be removed if it is overused. """ - if member: - await member.send(message) - await ctx.message.add_reaction("✅") - return - elif self.last_dm_user: - await self.last_dm_user.send(message) - await ctx.message.add_reaction("✅") - return - else: - log.debug("Unable to send a DM to the user.") + user_id = await self.dm_cache.get("last_user") + last_dm_user = ctx.guild.get_member(user_id) if user_id else None + + try: + if member: + await member.send(message) + await ctx.message.add_reaction("✅") + return + elif last_dm_user: + await last_dm_user.send(message) + await ctx.message.add_reaction("✅") + return + else: + log.debug("This bot has never gotten a DM, or the RedisCache has been cleared.") + await ctx.message.add_reaction("❌") + except discord.errors.Forbidden: + log.debug("User has disabled DMs.") await ctx.message.add_reaction("❌") async def fetch_webhook(self) -> None: @@ -74,7 +84,7 @@ class DMRelay(Cog): username=message.author.display_name, avatar_url=message.author.avatar_url ) - self.last_dm_user = message.author + await self.dm_cache.set("last_user", message.author.id) # Handle any attachments if message.attachments: -- cgit v1.2.3 From 1fb9bdb0deb3609f426a3bca555c67d0a7dc52a7 Mon Sep 17 00:00:00 2001 From: Slushie Date: Tue, 14 Jul 2020 00:39:31 +0100 Subject: fix misaligned indentation --- bot/cogs/filtering.py | 74 +++++++++++++++++++++++++-------------------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/bot/cogs/filtering.py b/bot/cogs/filtering.py index ec6769f68..2de00f3a1 100644 --- a/bot/cogs/filtering.py +++ b/bot/cogs/filtering.py @@ -217,43 +217,43 @@ class Filtering(Cog, Scheduler): if _filter["enabled"] and _filter["content_only"]: match = await _filter["function"](result) - if match: - # If this is a filter (not a watchlist), we set the variable so we know - # that it has been triggered - if _filter["type"] == "filter": - filter_triggered = True - - # We do not have to check against DM channels since !eval cannot be used there. - channel_str = f"in {msg.channel.mention}" - - message_content, additional_embeds, additional_embeds_msg = self._add_stats( - filter_name, match, result - ) - - message = ( - f"The {filter_name} {_filter['type']} was triggered " - f"by **{msg.author}** " - f"(`{msg.author.id}`) {channel_str} using !eval with " - f"[the following message]({msg.jump_url}):\n\n" - f"{message_content}" - ) - - log.debug(message) - - # Send pretty mod log embed to mod-alerts - await self.mod_log.send_log_message( - icon_url=Icons.filtering, - colour=Colour(Colours.soft_red), - title=f"{_filter['type'].title()} triggered!", - text=message, - thumbnail=msg.author.avatar_url_as(static_format="png"), - channel_id=Channels.mod_alerts, - ping_everyone=Filter.ping_everyone, - additional_embeds=additional_embeds, - additional_embeds_msg=additional_embeds_msg - ) - - break # We don't want multiple filters to trigger + if match: + # If this is a filter (not a watchlist), we set the variable so we know + # that it has been triggered + if _filter["type"] == "filter": + filter_triggered = True + + # We do not have to check against DM channels since !eval cannot be used there. + channel_str = f"in {msg.channel.mention}" + + message_content, additional_embeds, additional_embeds_msg = self._add_stats( + filter_name, match, result + ) + + message = ( + f"The {filter_name} {_filter['type']} was triggered " + f"by **{msg.author}** " + f"(`{msg.author.id}`) {channel_str} using !eval with " + f"[the following message]({msg.jump_url}):\n\n" + f"{message_content}" + ) + + log.debug(message) + + # Send pretty mod log embed to mod-alerts + await self.mod_log.send_log_message( + icon_url=Icons.filtering, + colour=Colour(Colours.soft_red), + title=f"{_filter['type'].title()} triggered!", + text=message, + thumbnail=msg.author.avatar_url_as(static_format="png"), + channel_id=Channels.mod_alerts, + ping_everyone=Filter.ping_everyone, + additional_embeds=additional_embeds, + additional_embeds_msg=additional_embeds_msg + ) + + break # We don't want multiple filters to trigger return filter_triggered -- cgit v1.2.3 From 7ff8b2c9ebc27194835c25258bc90c623bdbec6b Mon Sep 17 00:00:00 2001 From: kosayoda Date: Tue, 14 Jul 2020 10:51:56 +0800 Subject: Allow ordering watched users by oldest first --- bot/cogs/watchchannels/watchchannel.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/bot/cogs/watchchannels/watchchannel.py b/bot/cogs/watchchannels/watchchannel.py index 7c58a0fb5..2992a3085 100644 --- a/bot/cogs/watchchannels/watchchannel.py +++ b/bot/cogs/watchchannels/watchchannel.py @@ -287,7 +287,9 @@ class WatchChannel(metaclass=CogABCMeta): await self.webhook_send(embed=embed, username=msg.author.display_name, avatar_url=msg.author.avatar_url) - async def list_watched_users(self, ctx: Context, update_cache: bool = True) -> None: + async def list_watched_users( + self, ctx: Context, oldest_first: bool = False, update_cache: bool = True + ) -> None: """ Gives an overview of the watched user list for this channel. @@ -305,7 +307,11 @@ class WatchChannel(metaclass=CogABCMeta): time_delta = self._get_time_delta(inserted_at) lines.append(f"• <@{user_id}> (added {time_delta})") + if oldest_first: + lines.reverse() + lines = lines or ("There's nothing here yet.",) + embed = Embed( title=f"{self.__class__.__name__} watched users ({'updated' if update_cache else 'cached'})", color=Color.blue() -- cgit v1.2.3 From a6f66611b17aab8fbc3c54377c3971faeac5073b Mon Sep 17 00:00:00 2001 From: kosayoda Date: Tue, 14 Jul 2020 10:52:33 +0800 Subject: Pass argument as kwarg to preserve functionality --- bot/cogs/watchchannels/bigbrother.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/cogs/watchchannels/bigbrother.py b/bot/cogs/watchchannels/bigbrother.py index 702d371f4..fc899281b 100644 --- a/bot/cogs/watchchannels/bigbrother.py +++ b/bot/cogs/watchchannels/bigbrother.py @@ -42,7 +42,7 @@ class BigBrother(WatchChannel, Cog, name="Big Brother"): The optional kwarg `update_cache` can be used to update the user cache using the API before listing the users. """ - await self.list_watched_users(ctx, update_cache) + await self.list_watched_users(ctx, update_cache=update_cache) @bigbrother_group.command(name='watch', aliases=('w',)) @with_role(*MODERATION_ROLES) -- cgit v1.2.3 From ac7ed93eb64884a622c8718c8594aa74a3b2b201 Mon Sep 17 00:00:00 2001 From: kosayoda Date: Tue, 14 Jul 2020 10:58:02 +0800 Subject: Accept argument to order nominees by oldest first --- bot/cogs/watchchannels/talentpool.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/bot/cogs/watchchannels/talentpool.py b/bot/cogs/watchchannels/talentpool.py index 33550f68e..1f5989f23 100644 --- a/bot/cogs/watchchannels/talentpool.py +++ b/bot/cogs/watchchannels/talentpool.py @@ -38,14 +38,18 @@ class TalentPool(WatchChannel, Cog, name="Talentpool"): @nomination_group.command(name='watched', aliases=('all', 'list')) @with_role(*MODERATION_ROLES) - async def watched_command(self, ctx: Context, update_cache: bool = True) -> None: + async def watched_command( + self, ctx: Context, oldest_first: bool = False, update_cache: bool = True + ) -> None: """ Shows the users that are currently being monitored in the talent pool. + The optional kwarg `oldest_first` can be used to order the list by oldest nomination. + The optional kwarg `update_cache` can be used to update the user cache using the API before listing the users. """ - await self.list_watched_users(ctx, update_cache) + await self.list_watched_users(ctx, oldest_first=oldest_first, update_cache=update_cache) @nomination_group.command(name='watch', aliases=('w', 'add', 'a')) @with_role(*STAFF_ROLES) -- cgit v1.2.3 From 01d2803b608407330959ef880bd562456921d0fd Mon Sep 17 00:00:00 2001 From: kosayoda Date: Tue, 14 Jul 2020 10:58:56 +0800 Subject: Add command to list nominees by oldest first --- bot/cogs/watchchannels/talentpool.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/bot/cogs/watchchannels/talentpool.py b/bot/cogs/watchchannels/talentpool.py index 1f5989f23..89256e92e 100644 --- a/bot/cogs/watchchannels/talentpool.py +++ b/bot/cogs/watchchannels/talentpool.py @@ -51,6 +51,17 @@ class TalentPool(WatchChannel, Cog, name="Talentpool"): """ await self.list_watched_users(ctx, oldest_first=oldest_first, update_cache=update_cache) + @nomination_group.command(name='oldest') + @with_role(*MODERATION_ROLES) + async def oldest_command(self, ctx: Context, update_cache: bool = True) -> None: + """ + Shows talent pool monitored users ordered by oldest nomination. + + The optional kwarg `update_cache` can be used to update the user + cache using the API before listing the users. + """ + await ctx.invoke(self.watched_command, oldest_first=True, update_cache=update_cache) + @nomination_group.command(name='watch', aliases=('w', 'add', 'a')) @with_role(*STAFF_ROLES) async def watch_command(self, ctx: Context, user: FetchedMember, *, reason: str) -> None: -- cgit v1.2.3 From 28fe47d5d2404cdc70eaabe3e6c41567b9fd7c3d Mon Sep 17 00:00:00 2001 From: kosayoda Date: Tue, 14 Jul 2020 11:55:00 +0800 Subject: Achieve feature parity with talentpool --- bot/cogs/watchchannels/bigbrother.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/bot/cogs/watchchannels/bigbrother.py b/bot/cogs/watchchannels/bigbrother.py index fc899281b..4d27a6333 100644 --- a/bot/cogs/watchchannels/bigbrother.py +++ b/bot/cogs/watchchannels/bigbrother.py @@ -35,14 +35,29 @@ class BigBrother(WatchChannel, Cog, name="Big Brother"): @bigbrother_group.command(name='watched', aliases=('all', 'list')) @with_role(*MODERATION_ROLES) - async def watched_command(self, ctx: Context, update_cache: bool = True) -> None: + async def watched_command( + self, ctx: Context, oldest_first: bool = False, update_cache: bool = True + ) -> None: """ Shows the users that are currently being monitored by Big Brother. + The optional kwarg `oldest_first` can be used to order the list by oldest watched. + + The optional kwarg `update_cache` can be used to update the user + cache using the API before listing the users. + """ + await self.list_watched_users(ctx, oldest_first=oldest_first, update_cache=update_cache) + + @bigbrother_group.command(name='oldest') + @with_role(*MODERATION_ROLES) + async def oldest_command(self, ctx: Context, update_cache: bool = True) -> None: + """ + Shows Big Brother monitored users ordered by oldest watched. + The optional kwarg `update_cache` can be used to update the user cache using the API before listing the users. """ - await self.list_watched_users(ctx, update_cache=update_cache) + await ctx.invoke(self.watched_command, oldest_first=True, update_cache=update_cache) @bigbrother_group.command(name='watch', aliases=('w',)) @with_role(*MODERATION_ROLES) -- cgit v1.2.3 From 042f472ac3207ad685a5acb659a5a69f22c72282 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Wed, 15 Jul 2020 01:09:35 +0200 Subject: Remove caching of last_dm_user. If you're typing up a reply and the bot gets another DM while you're typing, you might accidentally send your reply to the wrong person. This could happen even if you're very attentive, because it might be a matter of milliseconds. The complexity to prevent this isn't worth the convenience of the feature, and it's nice to get rid of the caching as well, so I've decided to just make .reply require a user for every reply. https://github.com/python-discord/bot/issues/1041 --- bot/cogs/dm_relay.py | 42 +++++++++++++++++------------------------- bot/constants.py | 2 ++ config-default.yml | 1 + 3 files changed, 20 insertions(+), 25 deletions(-) diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py index 3fce52b93..f62d6105e 100644 --- a/bot/cogs/dm_relay.py +++ b/bot/cogs/dm_relay.py @@ -1,5 +1,4 @@ import logging -from typing import Optional import discord from discord import Color @@ -8,9 +7,7 @@ from discord.ext.commands import Cog from bot import constants from bot.bot import Bot -from bot.constants import MODERATION_ROLES -from bot.utils import RedisCache -from bot.utils.checks import with_role_check +from bot.utils.checks import in_whitelist_check, with_role_check from bot.utils.messages import send_attachments from bot.utils.webhooks import send_webhook @@ -20,9 +17,6 @@ log = logging.getLogger(__name__) class DMRelay(Cog): """Relay direct messages to and from the bot.""" - # RedisCache[str, t.Union[discord.User.id, discord.Member.id]] - dm_cache = RedisCache() - def __init__(self, bot: Bot): self.bot = bot self.webhook_id = constants.Webhooks.dm_log @@ -30,11 +24,11 @@ class DMRelay(Cog): self.bot.loop.create_task(self.fetch_webhook()) @commands.command(aliases=("reply",)) - async def send_dm(self, ctx: commands.Context, member: Optional[discord.Member], *, message: str) -> None: + async def send_dm(self, ctx: commands.Context, member: discord.Member, *, message: str) -> None: """ Allows you to send a DM to a user from the bot. - If `member` is not provided, it will send to the last user who DM'd the bot. + A `member` must be provided. This feature should be used extremely sparingly. Use ModMail if you need to have a serious conversation with a user. This is just for responding to extraordinary DMs, having a little @@ -42,21 +36,11 @@ class DMRelay(Cog): NOTE: This feature will be removed if it is overused. """ - user_id = await self.dm_cache.get("last_user") - last_dm_user = ctx.guild.get_member(user_id) if user_id else None - try: - if member: - await member.send(message) - await ctx.message.add_reaction("✅") - return - elif last_dm_user: - await last_dm_user.send(message) - await ctx.message.add_reaction("✅") - return - else: - log.debug("This bot has never gotten a DM, or the RedisCache has been cleared.") - await ctx.message.add_reaction("❌") + await member.send(message) + await ctx.message.add_reaction("✅") + return + except discord.errors.Forbidden: log.debug("User has disabled DMs.") await ctx.message.add_reaction("❌") @@ -84,7 +68,6 @@ class DMRelay(Cog): username=message.author.display_name, avatar_url=message.author.avatar_url ) - await self.dm_cache.set("last_user", message.author.id) # Handle any attachments if message.attachments: @@ -106,7 +89,16 @@ class DMRelay(Cog): def cog_check(self, ctx: commands.Context) -> bool: """Only allow moderators to invoke the commands in this cog.""" - return with_role_check(ctx, *MODERATION_ROLES) + checks = [ + with_role_check(ctx, *constants.MODERATION_ROLES), + in_whitelist_check( + ctx, + channels=[constants.Channels.dm_log], + redirect=None, + fail_silently=True, + ) + ] + return all(checks) def setup(bot: Bot) -> None: diff --git a/bot/constants.py b/bot/constants.py index 3f44003a8..778bc093c 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -395,6 +395,7 @@ class Channels(metaclass=YAMLGetter): dev_contrib: int dev_core: int dev_log: int + dm_log: int esoteric: int helpers: int how_to_get_help: int @@ -461,6 +462,7 @@ class Guild(metaclass=YAMLGetter): staff_channels: List[int] staff_roles: List[int] + class Keys(metaclass=YAMLGetter): section = "keys" diff --git a/config-default.yml b/config-default.yml index d12b9be27..8061e5e16 100644 --- a/config-default.yml +++ b/config-default.yml @@ -150,6 +150,7 @@ guild: mod_log: &MOD_LOG 282638479504965634 user_log: 528976905546760203 voice_log: 640292421988646961 + dm_log: 653713721625018428 # Off-topic off_topic_0: 291284109232308226 -- cgit v1.2.3 From 867b561a6ce4aff85451d00794c22e02793c8dac Mon Sep 17 00:00:00 2001 From: MarkKoz Date: Tue, 14 Jul 2020 17:07:35 -0700 Subject: Suppress NotFound when removing help cmd reactions The message may be deleted somehow before the wait_for times out. Fixes #1050 Fixes BOT-6X --- bot/cogs/help.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/bot/cogs/help.py b/bot/cogs/help.py index 832f6ea6b..70e62d590 100644 --- a/bot/cogs/help.py +++ b/bot/cogs/help.py @@ -36,13 +36,12 @@ async def help_cleanup(bot: Bot, author: Member, message: Message) -> None: await message.add_reaction(DELETE_EMOJI) - try: - await bot.wait_for("reaction_add", check=check, timeout=300) - await message.delete() - except TimeoutError: - await message.remove_reaction(DELETE_EMOJI, bot.user) - except NotFound: - pass + with suppress(NotFound): + try: + await bot.wait_for("reaction_add", check=check, timeout=300) + await message.delete() + except TimeoutError: + await message.remove_reaction(DELETE_EMOJI, bot.user) class HelpQueryNotFound(ValueError): -- cgit v1.2.3 From 992f3c47d328821bcf647df7683fd5ca8bd780aa Mon Sep 17 00:00:00 2001 From: MarkKoz Date: Tue, 14 Jul 2020 18:20:52 -0700 Subject: HelpChannels: remove cooldown info from available message Users can no longer see available channels if they're on cooldown. They will instead see a special "cooldown" channel which will explain what's going on. --- bot/cogs/help_channels.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/bot/cogs/help_channels.py b/bot/cogs/help_channels.py index 4d0c534b0..0c8cbb417 100644 --- a/bot/cogs/help_channels.py +++ b/bot/cogs/help_channels.py @@ -34,9 +34,6 @@ and will be yours until it has been inactive for {constants.HelpChannels.idle_mi is closed manually with `!close`. When that happens, it will be set to **dormant** and moved into \ the **Help: Dormant** category. -You may claim a new channel once every {constants.HelpChannels.claim_minutes} minutes. If you \ -currently cannot send a message in this channel, it means you are on cooldown and need to wait. - Try to write the best question you can by providing a detailed description and telling us what \ you've tried already. For more information on asking a good question, \ check out our guide on [asking good questions]({ASKING_GUIDE_URL}). -- cgit v1.2.3 From e46385d656129e06dd267764811d10ef5e8cd5a2 Mon Sep 17 00:00:00 2001 From: kosayoda Date: Wed, 15 Jul 2020 11:06:03 +0800 Subject: Document new kwarg in docstring --- bot/cogs/watchchannels/watchchannel.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/bot/cogs/watchchannels/watchchannel.py b/bot/cogs/watchchannels/watchchannel.py index 2992a3085..044077350 100644 --- a/bot/cogs/watchchannels/watchchannel.py +++ b/bot/cogs/watchchannels/watchchannel.py @@ -293,6 +293,8 @@ class WatchChannel(metaclass=CogABCMeta): """ Gives an overview of the watched user list for this channel. + The optional kwarg `oldest_first` orders the list by oldest entry. + The optional kwarg `update_cache` specifies whether the cache should be refreshed by polling the API. """ -- cgit v1.2.3 From 6ccbb944a50058cea74bfdfe855a538b09ab67b7 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Wed, 15 Jul 2020 07:22:59 +0200 Subject: Restore DM user caching. This reverts commit 042f472a --- bot/cogs/dm_relay.py | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py index f62d6105e..9a68b5341 100644 --- a/bot/cogs/dm_relay.py +++ b/bot/cogs/dm_relay.py @@ -1,4 +1,5 @@ import logging +from typing import Optional import discord from discord import Color @@ -7,6 +8,7 @@ from discord.ext.commands import Cog from bot import constants from bot.bot import Bot +from bot.utils import RedisCache from bot.utils.checks import in_whitelist_check, with_role_check from bot.utils.messages import send_attachments from bot.utils.webhooks import send_webhook @@ -17,6 +19,9 @@ log = logging.getLogger(__name__) class DMRelay(Cog): """Relay direct messages to and from the bot.""" + # RedisCache[str, t.Union[discord.User.id, discord.Member.id]] + dm_cache = RedisCache() + def __init__(self, bot: Bot): self.bot = bot self.webhook_id = constants.Webhooks.dm_log @@ -24,11 +29,11 @@ class DMRelay(Cog): self.bot.loop.create_task(self.fetch_webhook()) @commands.command(aliases=("reply",)) - async def send_dm(self, ctx: commands.Context, member: discord.Member, *, message: str) -> None: + async def send_dm(self, ctx: commands.Context, member: Optional[discord.Member], *, message: str) -> None: """ Allows you to send a DM to a user from the bot. - A `member` must be provided. + If `member` is not provided, it will send to the last user who DM'd the bot. This feature should be used extremely sparingly. Use ModMail if you need to have a serious conversation with a user. This is just for responding to extraordinary DMs, having a little @@ -36,11 +41,21 @@ class DMRelay(Cog): NOTE: This feature will be removed if it is overused. """ - try: - await member.send(message) - await ctx.message.add_reaction("✅") - return + user_id = await self.dm_cache.get("last_user") + last_dm_user = ctx.guild.get_member(user_id) if user_id else None + try: + if member: + await member.send(message) + await ctx.message.add_reaction("✅") + return + elif last_dm_user: + await last_dm_user.send(message) + await ctx.message.add_reaction("✅") + return + else: + log.debug("This bot has never gotten a DM, or the RedisCache has been cleared.") + await ctx.message.add_reaction("❌") except discord.errors.Forbidden: log.debug("User has disabled DMs.") await ctx.message.add_reaction("❌") @@ -68,6 +83,7 @@ class DMRelay(Cog): username=message.author.display_name, avatar_url=message.author.avatar_url ) + await self.dm_cache.set("last_user", message.author.id) # Handle any attachments if message.attachments: -- cgit v1.2.3 From 226eb68a4d397c14c68566f60a2de4a3704cf696 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Wed, 15 Jul 2020 07:30:02 +0200 Subject: Add the user ID to the username in dm relays. Without this, it is difficult to know precisely who the user that is DMing us is, which might be useful to us. https://github.com/python-discord/bot/issues/1041 --- bot/cogs/dm_relay.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py index 9a68b5341..d3637d34b 100644 --- a/bot/cogs/dm_relay.py +++ b/bot/cogs/dm_relay.py @@ -80,7 +80,7 @@ class DMRelay(Cog): await send_webhook( webhook=self.webhook, content=message.clean_content, - username=message.author.display_name, + username=f"{message.author.display_name} ({message.author.id})", avatar_url=message.author.avatar_url ) await self.dm_cache.set("last_user", message.author.id) -- cgit v1.2.3 From ed6d848e3cd5cf355b9702e9c8df08c063c11a47 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Wed, 15 Jul 2020 07:33:48 +0200 Subject: Add some stats for DMs sent and received. https://github.com/python-discord/bot/issues/1041 --- bot/cogs/dm_relay.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py index d3637d34b..edfcccf6d 100644 --- a/bot/cogs/dm_relay.py +++ b/bot/cogs/dm_relay.py @@ -48,10 +48,12 @@ class DMRelay(Cog): if member: await member.send(message) await ctx.message.add_reaction("✅") + self.bot.stats.incr("dm_relay.dm_sent") return elif last_dm_user: await last_dm_user.send(message) await ctx.message.add_reaction("✅") + self.bot.stats.incr("dm_relay.dm_sent") return else: log.debug("This bot has never gotten a DM, or the RedisCache has been cleared.") @@ -84,6 +86,7 @@ class DMRelay(Cog): avatar_url=message.author.avatar_url ) await self.dm_cache.set("last_user", message.author.id) + self.bot.stats.incr("dm_relay.dm_received") # Handle any attachments if message.attachments: -- cgit v1.2.3 From 90d2a77becb39d6b3c0056ea7c05b4a9e4d16f50 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Wed, 15 Jul 2020 10:15:08 +0200 Subject: Ves' refactor Co-authored-by: Sebastiaan Zeeff <33516116+SebastiaanZ@users.noreply.github.com> --- bot/cogs/dm_relay.py | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py index edfcccf6d..0c3eddf42 100644 --- a/bot/cogs/dm_relay.py +++ b/bot/cogs/dm_relay.py @@ -41,23 +41,24 @@ class DMRelay(Cog): NOTE: This feature will be removed if it is overused. """ - user_id = await self.dm_cache.get("last_user") - last_dm_user = ctx.guild.get_member(user_id) if user_id else None + if not member: + user_id = await self.dm_cache.get("last_user") + member = ctx.guild.get_member(user_id) if user_id else None + + # If we still don't have a Member at this point, give up + if not member: + log.debug("This bot has never gotten a DM, or the RedisCache has been cleared.") + await ctx.message.add_reaction("❌") + return try: - if member: - await member.send(message) - await ctx.message.add_reaction("✅") - self.bot.stats.incr("dm_relay.dm_sent") - return - elif last_dm_user: - await last_dm_user.send(message) - await ctx.message.add_reaction("✅") - self.bot.stats.incr("dm_relay.dm_sent") - return - else: - log.debug("This bot has never gotten a DM, or the RedisCache has been cleared.") - await ctx.message.add_reaction("❌") + await member.send(message) + except discord.errors.Forbidden: + log.debug("User has disabled DMs.") + await ctx.message.add_reaction("❌") + else: + await ctx.message.add_reaction("✅") + self.bot.stats.incr("dm_relay.dm_sent") except discord.errors.Forbidden: log.debug("User has disabled DMs.") await ctx.message.add_reaction("❌") -- cgit v1.2.3 From 403572b83cf3faea9068a25cb09e809d993c1514 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Wed, 15 Jul 2020 10:39:07 +0200 Subject: Create a UserMentionOrID converter. When we're using the !reply command, using a regular UserConverter is somewhat problematic. For example, if I wanted to send the message "lemon loves you", then I'd try to write `!reply lemon loves you` - however, the optional User converter would then try to convert `lemon` into a User, which it would successfully do since there's like 60 lemons on our server. As a result, the message "loves you" would be sent to a user called lemon.. god knows which one. To solve this bit of ambiguity, I introduce a new converter which only converts user mentions or user IDs into User, not strings that may be intended as part of the message you are sending. https://github.com/python-discord/bot/issues/1041 --- bot/cogs/dm_relay.py | 3 ++- bot/converters.py | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py index 0c3eddf42..c5a3dba22 100644 --- a/bot/cogs/dm_relay.py +++ b/bot/cogs/dm_relay.py @@ -8,6 +8,7 @@ from discord.ext.commands import Cog from bot import constants from bot.bot import Bot +from bot.converters import UserMentionOrID from bot.utils import RedisCache from bot.utils.checks import in_whitelist_check, with_role_check from bot.utils.messages import send_attachments @@ -29,7 +30,7 @@ class DMRelay(Cog): self.bot.loop.create_task(self.fetch_webhook()) @commands.command(aliases=("reply",)) - async def send_dm(self, ctx: commands.Context, member: Optional[discord.Member], *, message: str) -> None: + async def send_dm(self, ctx: commands.Context, member: Optional[UserMentionOrID], *, message: str) -> None: """ Allows you to send a DM to a user from the bot. diff --git a/bot/converters.py b/bot/converters.py index 898822165..7c62f92dd 100644 --- a/bot/converters.py +++ b/bot/converters.py @@ -330,6 +330,28 @@ def proxy_user(user_id: str) -> discord.Object: return user +class UserMentionOrID(UserConverter): + """ + Converts to a `discord.User`, but only if a mention or userID is provided. + + Unlike the default `UserConverter`, it does allow conversion from name, or name#descrim. + + This is useful in cases where that lookup strategy would lead to ambiguity. + """ + + async def convert(self, ctx: Context, argument: str) -> discord.User: + """Convert the `arg` to a `discord.User`.""" + print(argument) + match = self._get_id_match(argument) or re.match(r'<@!?([0-9]+)>$', argument) + + print(match) + + if match is not None: + return await super().convert(ctx, argument) + else: + raise BadArgument(f"`{argument}` is not a User mention or a User ID.") + + class FetchedUser(UserConverter): """ Converts to a `discord.User` or, if it fails, a `discord.Object`. -- cgit v1.2.3 From 80c1dbb240b744ceed5d1ea56c44c91d0014c304 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Wed, 15 Jul 2020 10:44:11 +0200 Subject: How did that except except block get in? Weird. https://github.com/python-discord/bot/issues/1041 --- bot/cogs/dm_relay.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/bot/cogs/dm_relay.py b/bot/cogs/dm_relay.py index c5a3dba22..0dc15d4b1 100644 --- a/bot/cogs/dm_relay.py +++ b/bot/cogs/dm_relay.py @@ -60,9 +60,6 @@ class DMRelay(Cog): else: await ctx.message.add_reaction("✅") self.bot.stats.incr("dm_relay.dm_sent") - except discord.errors.Forbidden: - log.debug("User has disabled DMs.") - await ctx.message.add_reaction("❌") async def fetch_webhook(self) -> None: """Fetches the webhook object, so we can post to it.""" -- cgit v1.2.3 From 14141a25bb87c298afae89886cb0ca3df65b9dee Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Wed, 15 Jul 2020 12:59:48 +0200 Subject: Oops, these prints shouldn't be here. https://github.com/python-discord/bot/issues/1041 --- bot/converters.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/bot/converters.py b/bot/converters.py index 7c62f92dd..4a0633951 100644 --- a/bot/converters.py +++ b/bot/converters.py @@ -341,11 +341,8 @@ class UserMentionOrID(UserConverter): async def convert(self, ctx: Context, argument: str) -> discord.User: """Convert the `arg` to a `discord.User`.""" - print(argument) match = self._get_id_match(argument) or re.match(r'<@!?([0-9]+)>$', argument) - print(match) - if match is not None: return await super().convert(ctx, argument) else: -- cgit v1.2.3