aboutsummaryrefslogtreecommitdiffstats
path: root/bot
diff options
context:
space:
mode:
authorGravatar Chris Lovering <[email protected]>2022-06-28 22:35:37 +0100
committerGravatar Chris Lovering <[email protected]>2022-09-21 23:02:55 +0100
commit10cf0802af4ba491f0b714a81f16637fadfd5810 (patch)
treeac12e5b03947e6c96250cce94733fba80756ada7 /bot
parentDon't override default flake8 ignore list (diff)
Use monkey patches from botcore
Diffstat (limited to 'bot')
-rw-r--r--bot/__init__.py20
-rw-r--r--bot/monkey_patches.py91
2 files changed, 3 insertions, 108 deletions
diff --git a/bot/__init__.py b/bot/__init__.py
index 3136c863..c1ecb30f 100644
--- a/bot/__init__.py
+++ b/bot/__init__.py
@@ -8,15 +8,14 @@ except ModuleNotFoundError:
import asyncio
import logging
import os
-from functools import partial, partialmethod
import arrow
import sentry_sdk
-from discord.ext import commands
+from botcore.utils import apply_monkey_patches
from sentry_sdk.integrations.logging import LoggingIntegration
from sentry_sdk.integrations.redis import RedisIntegration
-from bot import log, monkey_patches
+from bot import log
sentry_logging = LoggingIntegration(
level=logging.DEBUG,
@@ -41,17 +40,4 @@ start_time = arrow.utcnow()
if os.name == "nt":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
-monkey_patches.patch_typing()
-
-# This patches any convertors that use PartialMessage, but not the PartialMessageConverter itself
-# as library objects are made by this mapping.
-# https://github.com/Rapptz/discord.py/blob/1a4e73d59932cdbe7bf2c281f25e32529fc7ae1f/discord/ext/commands/converter.py#L984-L1004
-commands.converter.PartialMessageConverter = monkey_patches.FixedPartialMessageConverter
-
-# Monkey-patch discord.py decorators to use the both the Command and Group subclasses which supports root aliases.
-# Must be patched before any cogs are added.
-commands.command = partial(commands.command, cls=monkey_patches.Command)
-commands.GroupMixin.command = partialmethod(commands.GroupMixin.command, cls=monkey_patches.Command)
-
-commands.group = partial(commands.group, cls=monkey_patches.Group)
-commands.GroupMixin.group = partialmethod(commands.GroupMixin.group, cls=monkey_patches.Group)
+apply_monkey_patches()
diff --git a/bot/monkey_patches.py b/bot/monkey_patches.py
deleted file mode 100644
index 925d3206..00000000
--- a/bot/monkey_patches.py
+++ /dev/null
@@ -1,91 +0,0 @@
-import logging
-import re
-from datetime import datetime, timedelta
-
-from discord import Forbidden, http
-from discord.ext import commands
-
-log = logging.getLogger(__name__)
-MESSAGE_ID_RE = re.compile(r"(?P<message_id>[0-9]{15,20})$")
-
-
-class Command(commands.Command):
- """
- A `discord.ext.commands.Command` subclass which supports root aliases.
-
- A `root_aliases` keyword argument is added, which is a sequence of alias names that will act as
- top-level commands rather than being aliases of the command's group. It's stored as an attribute
- also named `root_aliases`.
- """
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.root_aliases = kwargs.get("root_aliases", [])
-
- if not isinstance(self.root_aliases, (list, tuple)):
- raise TypeError("Root aliases of a command must be a list or a tuple of strings.")
-
-
-class Group(commands.Group):
- """
- A `discord.ext.commands.Group` subclass which supports root aliases.
-
- A `root_aliases` keyword argument is added, which is a sequence of alias names that will act as
- top-level groups rather than being aliases of the command's group. It's stored as an attribute
- also named `root_aliases`.
- """
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.root_aliases = kwargs.get("root_aliases", [])
-
- if not isinstance(self.root_aliases, (list, tuple)):
- raise TypeError("Root aliases of a group must be a list or a tuple of strings.")
-
-
-def patch_typing() -> None:
- """
- Sometimes discord turns off typing events by throwing 403's.
-
- Handle those issues by patching the trigger_typing method so it ignores 403's in general.
- """
- log.debug("Patching send_typing, which should fix things breaking when discord disables typing events. Stay safe!")
-
- original = http.HTTPClient.send_typing
- last_403 = None
-
- async def honeybadger_type(self, channel_id: int) -> None: # noqa: ANN001
- nonlocal last_403
- if last_403 and (datetime.utcnow() - last_403) < timedelta(minutes=5):
- log.warning("Not sending typing event, we got a 403 less than 5 minutes ago.")
- return
- try:
- await original(self, channel_id)
- except Forbidden:
- last_403 = datetime.utcnow()
- log.warning("Got a 403 from typing event!")
- pass
-
- http.HTTPClient.send_typing = honeybadger_type
-
-
-class FixedPartialMessageConverter(commands.PartialMessageConverter):
- """
- Make the Message converter infer channelID from the given context if only a messageID is given.
-
- Discord.py's Message converter is supposed to infer channelID based
- on ctx.channel if only a messageID is given. A refactor commit, linked below,
- a few weeks before d.py's archival broke this defined behaviour of the converter.
- Currently, if only a messageID is given to the converter, it will only find that message
- if it's in the bot's cache.
-
- https://github.com/Rapptz/discord.py/commit/1a4e73d59932cdbe7bf2c281f25e32529fc7ae1f
- """
-
- @staticmethod
- def _get_id_matches(ctx: commands.Context, argument: str) -> tuple[int, int, int]:
- """Inserts ctx.channel.id before calling super method if argument is just a messageID."""
- match = MESSAGE_ID_RE.match(argument)
- if match:
- argument = f"{ctx.channel.id}-{match.group('message_id')}"
- return commands.PartialMessageConverter._get_id_matches(ctx, argument)