|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import re |
| 4 | + |
| 5 | +import aiohttp |
| 6 | +import discord |
| 7 | +from discord.ext import commands |
| 8 | +from pydis_core.utils import paste_service |
| 9 | + |
| 10 | +from bot.bot import Bot |
| 11 | +from bot.constants import Emojis |
| 12 | +from bot.log import get_logger |
| 13 | + |
| 14 | +log = get_logger(__name__) |
| 15 | + |
| 16 | +UPLOAD_EMOJI = Emojis.check_mark |
| 17 | +DELETE_EMOJI = Emojis.trashcan |
| 18 | + |
| 19 | + |
| 20 | +class AutoTextAttachmentUploader(commands.Cog): |
| 21 | + """ |
| 22 | + Handles automatic uploading of attachments to the paste bin. |
| 23 | +
|
| 24 | + Whenever a user uploads one or more attachments that is text-based (py, txt, csv, etc.), this cog offers to upload |
| 25 | + all the attachments to the paste bin automatically. The steps are as follows: |
| 26 | + - The bot replies to the message containing the attachments, asking the user to react with a checkmark to consent |
| 27 | + to having the content uploaded. |
| 28 | + - If consent is given, the bot uploads the contents and edits its own message to contain the link. |
| 29 | + - The bot DMs the user the delete link for the paste. |
| 30 | + - The bot waits for the user to react with a trashcan emoji, in which case the bot deletes the paste and its own |
| 31 | + message. |
| 32 | + """ |
| 33 | + |
| 34 | + def __init__(self, bot: Bot): |
| 35 | + self.bot = bot |
| 36 | + self.pending_messages = set[int]() |
| 37 | + |
| 38 | + @staticmethod |
| 39 | + async def _convert_attachment(attachment: discord.Attachment) -> paste_service.PasteFile: |
| 40 | + """Converts an attachment to a PasteFile, according to the attachment's file encoding.""" |
| 41 | + encoding = re.search(r"charset=(\S+)", attachment.content_type).group(1) |
| 42 | + file_content_bytes = await attachment.read() |
| 43 | + file_content = file_content_bytes.decode(encoding) |
| 44 | + return paste_service.PasteFile(content=file_content, name=attachment.filename) |
| 45 | + |
| 46 | + async def wait_for_user_reaction( |
| 47 | + self, |
| 48 | + message: discord.Message, |
| 49 | + user: discord.User, |
| 50 | + emoji: str, |
| 51 | + timeout: float = 60, |
| 52 | + ) -> bool: |
| 53 | + """Wait for `timeout` seconds for `user` to react to `message` with `emoji`.""" |
| 54 | + def wait_for_reaction(reaction: discord.Reaction, reactor: discord.User) -> bool: |
| 55 | + return ( |
| 56 | + reaction.message.id == message.id |
| 57 | + and str(reaction.emoji) == emoji |
| 58 | + and reactor == user |
| 59 | + ) |
| 60 | + |
| 61 | + await message.add_reaction(emoji) |
| 62 | + log.trace(f"Waiting for {user.name} to react to {message.id} with {emoji}") |
| 63 | + |
| 64 | + try: |
| 65 | + await self.bot.wait_for("reaction_add", timeout=timeout, check=wait_for_reaction) |
| 66 | + except TimeoutError: |
| 67 | + log.trace(f"User {user.name} did not react to message {message.id} with {emoji}") |
| 68 | + await message.clear_reactions() |
| 69 | + return False |
| 70 | + |
| 71 | + return True |
| 72 | + |
| 73 | + @commands.Cog.listener() |
| 74 | + async def on_message_delete(self, message: discord.Message) -> None: |
| 75 | + """Allows us to know which messages with attachments have been deleted.""" |
| 76 | + self.pending_messages.discard(message.id) |
| 77 | + |
| 78 | + @commands.Cog.listener() |
| 79 | + async def on_message(self, message: discord.Message) -> None: |
| 80 | + """Listens for messages containing attachments and offers to upload them to the pastebin.""" |
| 81 | + # Check if the message contains an embedded file and is not sent by a bot. |
| 82 | + if message.author.bot or not any("charset" in a.content_type for a in message.attachments): |
| 83 | + return |
| 84 | + |
| 85 | + log.trace(f"Offering to upload attachments for {message.author} in {message.channel}, message {message.id}") |
| 86 | + self.pending_messages.add(message.id) |
| 87 | + |
| 88 | + # Offer to upload the attachments and wait for the user's reaction. |
| 89 | + bot_reply = await message.reply( |
| 90 | + f"Please react with {UPLOAD_EMOJI} to upload your file(s) to our " |
| 91 | + f"[paste bin](<https://paste.pythondiscord.com/>), which is more accessible for some users." |
| 92 | + ) |
| 93 | + |
| 94 | + permission_granted = await self.wait_for_user_reaction(bot_reply, message.author, UPLOAD_EMOJI, 60. * 3) |
| 95 | + |
| 96 | + if not permission_granted: |
| 97 | + log.trace(f"{message.author} didn't give permission to upload {message.id} content; aborting.") |
| 98 | + await bot_reply.edit(content=f"~~{bot_reply.content}~~") |
| 99 | + return |
| 100 | + |
| 101 | + if message.id not in self.pending_messages: |
| 102 | + log.trace(f"{message.author}'s message was deleted before the attachments could be uploaded; aborting.") |
| 103 | + await bot_reply.delete() |
| 104 | + return |
| 105 | + |
| 106 | + # In either case, we do not want the message ID in pending_messages anymore. |
| 107 | + self.pending_messages.discard(message.id) |
| 108 | + |
| 109 | + # Extract the attachments. |
| 110 | + files = [ |
| 111 | + await self._convert_attachment(f) |
| 112 | + for f in message.attachments |
| 113 | + if "charset" in f.content_type |
| 114 | + ] |
| 115 | + |
| 116 | + # Upload the files to the paste bin, exiting early if there's an error. |
| 117 | + log.trace(f"Attempting to upload {len(files)} file(s) to pastebin.") |
| 118 | + try: |
| 119 | + async with aiohttp.ClientSession() as session: |
| 120 | + paste_response = await paste_service.send_to_paste_service(files=files, http_session=session) |
| 121 | + except (paste_service.PasteTooLongError, ValueError): |
| 122 | + log.trace(f"{message.author}'s attachments were too long.") |
| 123 | + await bot_reply.edit(content="Your paste is too long, and couldn't be uploaded.") |
| 124 | + return |
| 125 | + except paste_service.PasteUploadError: |
| 126 | + log.trace(f"Unexpected error uploading {message.author}'s attachments.") |
| 127 | + await bot_reply.edit(content="There was an error uploading your paste.") |
| 128 | + return |
| 129 | + |
| 130 | + # Send the user a DM with the delete link for the paste. |
| 131 | + # The angle brackets around the remove link are required to stop Discord from visiting the URL to produce a |
| 132 | + # preview, thereby deleting the paste |
| 133 | + await message.author.send(content=f"[Click here](<{paste_response.removal}>) to delete your recent paste.") |
| 134 | + |
| 135 | + # Edit the bot message to contain the link to the paste. |
| 136 | + await bot_reply.edit(content=f"[Click here]({paste_response.link}) to see this code in our pastebin.") |
| 137 | + await bot_reply.clear_reactions() |
| 138 | + await bot_reply.add_reaction(DELETE_EMOJI) |
| 139 | + |
| 140 | + # Wait for the user to react with a trash can, which they can use to delete the paste. |
| 141 | + log.trace(f"Offering to delete {message.author}'s attachments in {message.channel}, message {message.id}") |
| 142 | + user_wants_delete = await self.wait_for_user_reaction(bot_reply, message.author, DELETE_EMOJI, 60. * 10) |
| 143 | + |
| 144 | + if not user_wants_delete: |
| 145 | + return |
| 146 | + |
| 147 | + # Delete the paste and the bot's message. |
| 148 | + async with aiohttp.ClientSession() as session: |
| 149 | + await session.get(paste_response.removal) |
| 150 | + |
| 151 | + await bot_reply.delete() |
| 152 | + |
| 153 | + |
| 154 | +async def setup(bot: Bot) -> None: |
| 155 | + """Load the EmbedFileHandler cog.""" |
| 156 | + await bot.add_cog(AutoTextAttachmentUploader(bot)) |
0 commit comments