|
| 1 | +from discord.ext import commands |
| 2 | + |
| 3 | +from bot import ModmailBot |
| 4 | +from core import time |
| 5 | + |
| 6 | + |
| 7 | +class StrictUserFriendlyDuration(time.UserFriendlyTime): |
| 8 | + """ |
| 9 | + A converter which parses user-friendly time durations. |
| 10 | +
|
| 11 | + Since this converter is meant for parsing close messages while |
| 12 | + closing threads, both custom close messages and time durations are |
| 13 | + parsed. |
| 14 | +
|
| 15 | + Unlike the parent class, a time duration must be provided when |
| 16 | + a custom close message is provided. |
| 17 | + """ |
| 18 | + |
| 19 | + MODIFIERS = {'silently', 'silent', 'cancel'} |
| 20 | + |
| 21 | + async def convert(self, ctx: commands.Context, argument: str) -> "StrictUserFriendlyDuration": |
| 22 | + """ |
| 23 | + Parse the provided time duration along with any close message. |
| 24 | +
|
| 25 | + Fail if a custom close message is provided without a time |
| 26 | + duration. |
| 27 | + """ |
| 28 | + await super().convert(ctx, argument) |
| 29 | + |
| 30 | + argument_passed = bool(argument) |
| 31 | + not_a_modifier = argument not in self.MODIFIERS |
| 32 | + if argument_passed and not_a_modifier and self.arg == argument: |
| 33 | + # Fail since only a close message was provided. |
| 34 | + raise commands.BadArgument("A time duration must be provided when closing with a custom message.") |
| 35 | + |
| 36 | + return self |
| 37 | + |
| 38 | + |
| 39 | +ADDED_HELP_TEXT = '\n\n*Note: Providing a time duration is necessary when closing with a custom message.*' |
| 40 | + |
| 41 | + |
| 42 | +def setup(bot: ModmailBot) -> None: |
| 43 | + """ |
| 44 | + Monkey patch the close command's callback. |
| 45 | +
|
| 46 | + This makes it use the StrictUserFriendlyTime converter and updates |
| 47 | + the help text to reflect the new behaviour.. |
| 48 | + """ |
| 49 | + global previous_converter |
| 50 | + |
| 51 | + command = bot.get_command('close') |
| 52 | + |
| 53 | + previous_converter = command.callback.__annotations__['after'] |
| 54 | + command.callback.__annotations__['after'] = StrictUserFriendlyDuration |
| 55 | + command.callback = command.callback |
| 56 | + |
| 57 | + command.help += ADDED_HELP_TEXT |
| 58 | + |
| 59 | + |
| 60 | +def teardown(bot: ModmailBot) -> None: |
| 61 | + """Undo changes to the close command.""" |
| 62 | + command = bot.get_command('close') |
| 63 | + |
| 64 | + command.callback.__annotations__['after'] = previous_converter |
| 65 | + command.callback = command.callback |
| 66 | + |
| 67 | + command.help = command.help.remove_suffix(ADDED_HELP_TEXT) |
0 commit comments