|
| 1 | +import typing as t |
| 2 | +from datetime import datetime |
| 3 | + |
| 4 | +import discord |
| 5 | +from aiohttp.client_exceptions import ClientResponseError |
| 6 | +from discord.ext import commands |
| 7 | + |
| 8 | +from bot import constants, logger |
| 9 | +from bot.bot import ThreadBot |
| 10 | +from bot.exts.ban_appeals import BASE_RESPONSE, _api_handlers, _models |
| 11 | + |
| 12 | + |
| 13 | +class BanAppeals(commands.Cog): |
| 14 | + """Cog for creating and actioning ban appeals threads when a user appeals via forms.""" |
| 15 | + |
| 16 | + def __init__(self, bot: ThreadBot) -> None: |
| 17 | + self.bot = bot |
| 18 | + self.appeal_channel: t.Optional[discord.TextChannel] = None |
| 19 | + self.cookies = {"token": constants.Secrets.forms_token} |
| 20 | + |
| 21 | + if constants.DEBUG_MODE: |
| 22 | + self.archive_time = constants.ThreadArchiveTimes.DAY.value |
| 23 | + else: |
| 24 | + self.archive_time = constants.ThreadArchiveTimes.WEEK.value |
| 25 | + |
| 26 | + self.init_task = self.bot.loop.create_task(self.init_cog()) |
| 27 | + |
| 28 | + async def init_cog(self) -> None: |
| 29 | + """Initialise the ban appeals system.""" |
| 30 | + logger.info("Waiting for the guild to be available before initialisation.") |
| 31 | + await self.bot.wait_until_guild_available() |
| 32 | + |
| 33 | + self.appeal_channel = self.bot.get_channel(constants.Channels.appeals) |
| 34 | + |
| 35 | + async def appeal_thread_check(self, ctx: commands.Context, messages: list[discord.Message]) -> bool: |
| 36 | + """Return True if channel is a Thread, in the appeal channel, with a first message sent from this bot.""" |
| 37 | + await self.init_task |
| 38 | + if not isinstance(ctx.channel, discord.Thread): |
| 39 | + # Channel isn't a discord.Thread |
| 40 | + return False |
| 41 | + if not ctx.channel.parent == self.appeal_channel: |
| 42 | + # Thread parent channel isn't the appeal channel. |
| 43 | + return False |
| 44 | + if not messages or not messages[1].author == ctx.guild.me: |
| 45 | + # This aren't messages in the channel, or the first message isn't from this bot. |
| 46 | + # Ignore messages[0], as it refers to the parent message. |
| 47 | + return False |
| 48 | + if messages[1].content.startswith("Actioned"): |
| 49 | + # Ignore appeals that have already been actioned. |
| 50 | + return False |
| 51 | + return True |
| 52 | + |
| 53 | + @commands.has_any_role(*constants.MODERATION_ROLES, constants.Roles.core_developers) |
| 54 | + @commands.group(name="appeal", invoke_without_command=True) |
| 55 | + async def ban_appeal(self, ctx: commands.Context) -> None: |
| 56 | + """Ban group for the ban appeal commands.""" |
| 57 | + await ctx.send_help(ctx.command) |
| 58 | + |
| 59 | + @commands.has_any_role(*constants.MODERATION_ROLES, constants.Roles.core_developers) |
| 60 | + @ban_appeal.command(name="test") |
| 61 | + async def embed_test(self, ctx: commands.Context) -> None: |
| 62 | + """Send a embed that mocks the ban appeal webhook.""" |
| 63 | + await self.init_task |
| 64 | + |
| 65 | + embed = discord.Embed( |
| 66 | + title="New Form Response", |
| 67 | + description=f"{ctx.author.mention} submitted a response to `Ban Appeals`.", |
| 68 | + colour=constants.Colours.info, |
| 69 | + url="https://forms-api.pythondiscord.com/forms/ban-appeals/responses/7fbb1a2e-d910-44bb-bcc7-e9fcfd04f758" |
| 70 | + ) |
| 71 | + embed.timestamp = datetime(year=2021, month=8, day=22, hour=12, minute=56, second=14) |
| 72 | + embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url) |
| 73 | + await self.appeal_channel.send("New ban appeal!", embed=embed) |
| 74 | + await ctx.message.add_reaction("✅") |
| 75 | + |
| 76 | + @commands.has_any_role(constants.Roles.admins) |
| 77 | + @ban_appeal.command(name="respond", aliases=("response",)) |
| 78 | + async def appeal_respond( |
| 79 | + self, |
| 80 | + ctx: commands.Context, |
| 81 | + response: _models.AppealResponse, |
| 82 | + *, |
| 83 | + extras: t.Optional[str] |
| 84 | + ) -> None: |
| 85 | + """ |
| 86 | + Respond to the appeal with the given response. |
| 87 | +
|
| 88 | + `extras` can be given to add extra content to the email. |
| 89 | + You will be asked to confirm the full email before it is sent. |
| 90 | + """ |
| 91 | + # Don't use a discord.py check to avoid fetching first message multiple times. |
| 92 | + messages = await ctx.channel.history(limit=2, oldest_first=True).flatten() |
| 93 | + if not await self.appeal_thread_check(ctx, messages): |
| 94 | + await ctx.message.add_reaction("❌") |
| 95 | + return |
| 96 | + thread_data_message = messages[1] |
| 97 | + response_uuid = thread_data_message.content.split(" ")[0] |
| 98 | + appeal_details: _models.AppealDetails = await _api_handlers.fetch_form_appeal_data( |
| 99 | + response_uuid, |
| 100 | + self.cookies, |
| 101 | + self.bot.http_session |
| 102 | + ) |
| 103 | + |
| 104 | + email_response_content = BASE_RESPONSE.format( |
| 105 | + name=appeal_details.appealer, |
| 106 | + snippet=response, |
| 107 | + extras=f"\n\n{extras}" if extras else "" |
| 108 | + ) |
| 109 | + await ctx.send( |
| 110 | + email_response_content, |
| 111 | + # This is commented out awaiting PyDis to get a new mail provider. |
| 112 | + # view=_models.ConfirmAppealResponse(thread_data_message, appeal_details.email) |
| 113 | + ) |
| 114 | + |
| 115 | + @commands.Cog.listener(name="on_message") |
| 116 | + async def ban_appeal_listener(self, message: discord.Message) -> None: |
| 117 | + """Listens for ban appeal embeds to trigger the appeal process.""" |
| 118 | + await self.init_task |
| 119 | + |
| 120 | + if not message.channel == self.appeal_channel: |
| 121 | + # Ignore messages not in the appeal channel |
| 122 | + return |
| 123 | + |
| 124 | + if not message.author.bot: |
| 125 | + # Ignore messages not from bots |
| 126 | + return |
| 127 | + |
| 128 | + if not message.embeds or len(message.embeds) != 1: |
| 129 | + # Ignore messages without extact 1 embed |
| 130 | + return |
| 131 | + |
| 132 | + appeal_details = await self.get_appeal_details_from_embed(message.embeds[0]) |
| 133 | + |
| 134 | + thread: discord.Thread = await message.create_thread( |
| 135 | + name=appeal_details.thread_name, |
| 136 | + auto_archive_duration=self.archive_time |
| 137 | + ) |
| 138 | + await thread.send(appeal_details) |
| 139 | + |
| 140 | + async def get_appeal_details_from_embed(self, embed: discord.Embed) -> _models.AppealDetails: |
| 141 | + """Extract a form response uuid from a ban appeal webhook message.""" |
| 142 | + response_uuid = embed.url.split("/")[-1] |
| 143 | + try: |
| 144 | + return await _api_handlers.fetch_form_appeal_data( |
| 145 | + response_uuid, |
| 146 | + self.cookies, |
| 147 | + self.bot.http_session |
| 148 | + ) |
| 149 | + except ClientResponseError as e: |
| 150 | + if e.status == 403: |
| 151 | + await self.appeal_channel.send(":x: Forms credentials are invalid, could not initiate appeal flow.") |
| 152 | + raise |
0 commit comments