We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Prepend emojis indicative of success for !eval
Comments on [org-issue-141](https://github.com/python-discord/organisation/issues/141) suggests something quite useful. 

Add emojis indicative of success when you use !eval. 

- ✅ - if no error.
- ❌ - if exception.
- ❗ - for other cases, as it runs but there's no output


![bild](https://user-images.githubusercontent.com/1515135/66685485-90e52600-ec31-11e9-9f42-d9c0da31a5c3.png)
![bild](https://user-images.githubusercontent.com/1515135/66685492-95114380-ec31-11e9-9154-77da46f11cde.png)
![bild](https://imgur.com/l10DMcQ.png)


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `bot/cogs/snekbox.py`
Content:
```
1 import datetime
2 import logging
3 import re
4 import textwrap
5 from signal import Signals
6 from typing import Optional, Tuple
7 
8 from discord.ext.commands import Bot, Cog, Context, command, guild_only
9 
10 from bot.constants import Channels, Roles, URLs
11 from bot.decorators import in_channel
12 from bot.utils.messages import wait_for_deletion
13 
14 log = logging.getLogger(__name__)
15 
16 ESCAPE_REGEX = re.compile("[`\u202E\u200B]{3,}")
17 FORMATTED_CODE_REGEX = re.compile(
18     r"^\s*"                                 # any leading whitespace from the beginning of the string
19     r"(?P<delim>(?P<block>```)|``?)"        # code delimiter: 1-3 backticks; (?P=block) only matches if it's a block
20     r"(?(block)(?:(?P<lang>[a-z]+)\n)?)"    # if we're in a block, match optional language (only letters plus newline)
21     r"(?:[ \t]*\n)*"                        # any blank (empty or tabs/spaces only) lines before the code
22     r"(?P<code>.*?)"                        # extract all code inside the markup
23     r"\s*"                                  # any more whitespace before the end of the code markup
24     r"(?P=delim)"                           # match the exact same delimiter from the start again
25     r"\s*$",                                # any trailing whitespace until the end of the string
26     re.DOTALL | re.IGNORECASE               # "." also matches newlines, case insensitive
27 )
28 RAW_CODE_REGEX = re.compile(
29     r"^(?:[ \t]*\n)*"                       # any blank (empty or tabs/spaces only) lines before the code
30     r"(?P<code>.*?)"                        # extract all the rest as code
31     r"\s*$",                                # any trailing whitespace until the end of the string
32     re.DOTALL                               # "." also matches newlines
33 )
34 
35 MAX_PASTE_LEN = 1000
36 EVAL_ROLES = (Roles.helpers, Roles.moderator, Roles.admin, Roles.owner, Roles.rockstars, Roles.partners)
37 
38 
39 class Snekbox(Cog):
40     """Safe evaluation of Python code using Snekbox."""
41 
42     def __init__(self, bot: Bot):
43         self.bot = bot
44         self.jobs = {}
45 
46     async def post_eval(self, code: str) -> dict:
47         """Send a POST request to the Snekbox API to evaluate code and return the results."""
48         url = URLs.snekbox_eval_api
49         data = {"input": code}
50         async with self.bot.http_session.post(url, json=data, raise_for_status=True) as resp:
51             return await resp.json()
52 
53     async def upload_output(self, output: str) -> Optional[str]:
54         """Upload the eval output to a paste service and return a URL to it if successful."""
55         log.trace("Uploading full output to paste service...")
56 
57         if len(output) > MAX_PASTE_LEN:
58             log.info("Full output is too long to upload")
59             return "too long to upload"
60 
61         url = URLs.paste_service.format(key="documents")
62         try:
63             async with self.bot.http_session.post(url, data=output, raise_for_status=True) as resp:
64                 data = await resp.json()
65 
66             if "key" in data:
67                 return URLs.paste_service.format(key=data["key"])
68         except Exception:
69             # 400 (Bad Request) means there are too many characters
70             log.exception("Failed to upload full output to paste service!")
71 
72     @staticmethod
73     def prepare_input(code: str) -> str:
74         """Extract code from the Markdown, format it, and insert it into the code template."""
75         match = FORMATTED_CODE_REGEX.fullmatch(code)
76         if match:
77             code, block, lang, delim = match.group("code", "block", "lang", "delim")
78             code = textwrap.dedent(code)
79             if block:
80                 info = (f"'{lang}' highlighted" if lang else "plain") + " code block"
81             else:
82                 info = f"{delim}-enclosed inline code"
83             log.trace(f"Extracted {info} for evaluation:\n{code}")
84         else:
85             code = textwrap.dedent(RAW_CODE_REGEX.fullmatch(code).group("code"))
86             log.trace(
87                 f"Eval message contains unformatted or badly formatted code, "
88                 f"stripping whitespace only:\n{code}"
89             )
90 
91         return code
92 
93     @staticmethod
94     def get_results_message(results: dict) -> Tuple[str, str]:
95         """Return a user-friendly message and error corresponding to the process's return code."""
96         stdout, returncode = results["stdout"], results["returncode"]
97         msg = f"Your eval job has completed with return code {returncode}"
98         error = ""
99 
100         if returncode is None:
101             msg = "Your eval job has failed"
102             error = stdout.strip()
103         elif returncode == 128 + Signals.SIGKILL:
104             msg = "Your eval job timed out or ran out of memory"
105         elif returncode == 255:
106             msg = "Your eval job has failed"
107             error = "A fatal NsJail error occurred"
108         else:
109             # Try to append signal's name if one exists
110             try:
111                 name = Signals(returncode - 128).name
112                 msg = f"{msg} ({name})"
113             except ValueError:
114                 pass
115 
116         return msg, error
117 
118     async def format_output(self, output: str) -> Tuple[str, Optional[str]]:
119         """
120         Format the output and return a tuple of the formatted output and a URL to the full output.
121 
122         Prepend each line with a line number. Truncate if there are over 10 lines or 1000 characters
123         and upload the full output to a paste service.
124         """
125         log.trace("Formatting output...")
126 
127         output = output.strip(" \n")
128         original_output = output  # To be uploaded to a pasting service if needed
129         paste_link = None
130 
131         if "<@" in output:
132             output = output.replace("<@", "<@\u200B")  # Zero-width space
133 
134         if "<!@" in output:
135             output = output.replace("<!@", "<!@\u200B")  # Zero-width space
136 
137         if ESCAPE_REGEX.findall(output):
138             return "Code block escape attempt detected; will not output result", paste_link
139 
140         truncated = False
141         lines = output.count("\n")
142 
143         if lines > 0:
144             output = output.split("\n")[:10]  # Only first 10 cause the rest is truncated anyway
145             output = (f"{i:03d} | {line}" for i, line in enumerate(output, 1))
146             output = "\n".join(output)
147 
148         if lines > 10:
149             truncated = True
150             if len(output) >= 1000:
151                 output = f"{output[:1000]}\n... (truncated - too long, too many lines)"
152             else:
153                 output = f"{output}\n... (truncated - too many lines)"
154         elif len(output) >= 1000:
155             truncated = True
156             output = f"{output[:1000]}\n... (truncated - too long)"
157 
158         if truncated:
159             paste_link = await self.upload_output(original_output)
160 
161         output = output.strip()
162         if not output:
163             output = "[No output]"
164 
165         return output, paste_link
166 
167     @command(name="eval", aliases=("e",))
168     @guild_only()
169     @in_channel(Channels.bot, bypass_roles=EVAL_ROLES)
170     async def eval_command(self, ctx: Context, *, code: str = None) -> None:
171         """
172         Run Python code and get the results.
173 
174         This command supports multiple lines of code, including code wrapped inside a formatted code
175         block. We've done our best to make this safe, but do let us know if you manage to find an
176         issue with it!
177         """
178         if ctx.author.id in self.jobs:
179             await ctx.send(
180                 f"{ctx.author.mention} You've already got a job running - "
181                 "please wait for it to finish!"
182             )
183             return
184 
185         if not code:  # None or empty string
186             await ctx.invoke(self.bot.get_command("help"), "eval")
187             return
188 
189         log.info(f"Received code from {ctx.author} for evaluation:\n{code}")
190 
191         self.jobs[ctx.author.id] = datetime.datetime.now()
192         code = self.prepare_input(code)
193 
194         try:
195             async with ctx.typing():
196                 results = await self.post_eval(code)
197                 msg, error = self.get_results_message(results)
198 
199                 if error:
200                     output, paste_link = error, None
201                 else:
202                     output, paste_link = await self.format_output(results["stdout"])
203 
204                 msg = f"{ctx.author.mention} {msg}.\n\n```py\n{output}\n```"
205                 if paste_link:
206                     msg = f"{msg}\nFull output: {paste_link}"
207 
208                 response = await ctx.send(msg)
209                 self.bot.loop.create_task(
210                     wait_for_deletion(response, user_ids=(ctx.author.id,), client=ctx.bot)
211                 )
212 
213                 log.info(f"{ctx.author}'s job had a return code of {results['returncode']}")
214         finally:
215             del self.jobs[ctx.author.id]
216 
217 
218 def setup(bot: Bot) -> None:
219     """Snekbox cog load."""
220     bot.add_cog(Snekbox(bot))
221     log.info("Cog loaded: Snekbox")
222
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/bot/cogs/snekbox.py b/bot/cogs/snekbox.py
--- a/bot/cogs/snekbox.py
+++ b/bot/cogs/snekbox.py
@@ -115,6 +115,16 @@
 
         return msg, error
 
+    @staticmethod
+    def get_status_emoji(results: dict) -> str:
+        """Return an emoji corresponding to the status code or lack of output in result."""
+        if not results["stdout"].strip():  # No output
+            return ":warning:"
+        elif results["returncode"] == 0:  # No error
+            return ":white_check_mark:"
+        else:  # Exception
+            return ":x:"
+
     async def format_output(self, output: str) -> Tuple[str, Optional[str]]:
         """
         Format the output and return a tuple of the formatted output and a URL to the full output.
@@ -201,7 +211,8 @@
                 else:
                     output, paste_link = await self.format_output(results["stdout"])
 
-                msg = f"{ctx.author.mention} {msg}.\n\n```py\n{output}\n```"
+                icon = self.get_status_emoji(results)
+                msg = f"{ctx.author.mention} {icon} {msg}.\n\n```py\n{output}\n```"
                 if paste_link:
                     msg = f"{msg}\nFull output: {paste_link}"

{"golden_diff": "diff --git a/bot/cogs/snekbox.py b/bot/cogs/snekbox.py\n--- a/bot/cogs/snekbox.py\n+++ b/bot/cogs/snekbox.py\n@@ -115,6 +115,16 @@\n \n         return msg, error\n \n+    @staticmethod\n+    def get_status_emoji(results: dict) -> str:\n+        \"\"\"Return an emoji corresponding to the status code or lack of output in result.\"\"\"\n+        if not results[\"stdout\"].strip():  # No output\n+            return \":warning:\"\n+        elif results[\"returncode\"] == 0:  # No error\n+            return \":white_check_mark:\"\n+        else:  # Exception\n+            return \":x:\"\n+\n     async def format_output(self, output: str) -> Tuple[str, Optional[str]]:\n         \"\"\"\n         Format the output and return a tuple of the formatted output and a URL to the full output.\n@@ -201,7 +211,8 @@\n                 else:\n                     output, paste_link = await self.format_output(results[\"stdout\"])\n \n-                msg = f\"{ctx.author.mention} {msg}.\\n\\n```py\\n{output}\\n```\"\n+                icon = self.get_status_emoji(results)\n+                msg = f\"{ctx.author.mention} {icon} {msg}.\\n\\n```py\\n{output}\\n```\"\n                 if paste_link:\n                     msg = f\"{msg}\\nFull output: {paste_link}\"\n", "issue": "Prepend emojis indicative of success for !eval\nComments on [org-issue-141](https://github.com/python-discord/organisation/issues/141) suggests something quite useful. \r\n\r\nAdd emojis indicative of success when you use !eval. \r\n\r\n- \u2705 - if no error.\r\n- \u274c - if exception.\r\n- \u2757 - for other cases, as it runs but there's no output\r\n\r\n\r\n![bild](https://user-images.githubusercontent.com/1515135/66685485-90e52600-ec31-11e9-9f42-d9c0da31a5c3.png)\r\n![bild](https://user-images.githubusercontent.com/1515135/66685492-95114380-ec31-11e9-9154-77da46f11cde.png)\r\n![bild](https://imgur.com/l10DMcQ.png)\r\n\n", "before_files": [{"content": "import datetime\nimport logging\nimport re\nimport textwrap\nfrom signal import Signals\nfrom typing import Optional, Tuple\n\nfrom discord.ext.commands import Bot, Cog, Context, command, guild_only\n\nfrom bot.constants import Channels, Roles, URLs\nfrom bot.decorators import in_channel\nfrom bot.utils.messages import wait_for_deletion\n\nlog = logging.getLogger(__name__)\n\nESCAPE_REGEX = re.compile(\"[`\\u202E\\u200B]{3,}\")\nFORMATTED_CODE_REGEX = re.compile(\n    r\"^\\s*\"                                 # any leading whitespace from the beginning of the string\n    r\"(?P<delim>(?P<block>```)|``?)\"        # code delimiter: 1-3 backticks; (?P=block) only matches if it's a block\n    r\"(?(block)(?:(?P<lang>[a-z]+)\\n)?)\"    # if we're in a block, match optional language (only letters plus newline)\n    r\"(?:[ \\t]*\\n)*\"                        # any blank (empty or tabs/spaces only) lines before the code\n    r\"(?P<code>.*?)\"                        # extract all code inside the markup\n    r\"\\s*\"                                  # any more whitespace before the end of the code markup\n    r\"(?P=delim)\"                           # match the exact same delimiter from the start again\n    r\"\\s*$\",                                # any trailing whitespace until the end of the string\n    re.DOTALL | re.IGNORECASE               # \".\" also matches newlines, case insensitive\n)\nRAW_CODE_REGEX = re.compile(\n    r\"^(?:[ \\t]*\\n)*\"                       # any blank (empty or tabs/spaces only) lines before the code\n    r\"(?P<code>.*?)\"                        # extract all the rest as code\n    r\"\\s*$\",                                # any trailing whitespace until the end of the string\n    re.DOTALL                               # \".\" also matches newlines\n)\n\nMAX_PASTE_LEN = 1000\nEVAL_ROLES = (Roles.helpers, Roles.moderator, Roles.admin, Roles.owner, Roles.rockstars, Roles.partners)\n\n\nclass Snekbox(Cog):\n    \"\"\"Safe evaluation of Python code using Snekbox.\"\"\"\n\n    def __init__(self, bot: Bot):\n        self.bot = bot\n        self.jobs = {}\n\n    async def post_eval(self, code: str) -> dict:\n        \"\"\"Send a POST request to the Snekbox API to evaluate code and return the results.\"\"\"\n        url = URLs.snekbox_eval_api\n        data = {\"input\": code}\n        async with self.bot.http_session.post(url, json=data, raise_for_status=True) as resp:\n            return await resp.json()\n\n    async def upload_output(self, output: str) -> Optional[str]:\n        \"\"\"Upload the eval output to a paste service and return a URL to it if successful.\"\"\"\n        log.trace(\"Uploading full output to paste service...\")\n\n        if len(output) > MAX_PASTE_LEN:\n            log.info(\"Full output is too long to upload\")\n            return \"too long to upload\"\n\n        url = URLs.paste_service.format(key=\"documents\")\n        try:\n            async with self.bot.http_session.post(url, data=output, raise_for_status=True) as resp:\n                data = await resp.json()\n\n            if \"key\" in data:\n                return URLs.paste_service.format(key=data[\"key\"])\n        except Exception:\n            # 400 (Bad Request) means there are too many characters\n            log.exception(\"Failed to upload full output to paste service!\")\n\n    @staticmethod\n    def prepare_input(code: str) -> str:\n        \"\"\"Extract code from the Markdown, format it, and insert it into the code template.\"\"\"\n        match = FORMATTED_CODE_REGEX.fullmatch(code)\n        if match:\n            code, block, lang, delim = match.group(\"code\", \"block\", \"lang\", \"delim\")\n            code = textwrap.dedent(code)\n            if block:\n                info = (f\"'{lang}' highlighted\" if lang else \"plain\") + \" code block\"\n            else:\n                info = f\"{delim}-enclosed inline code\"\n            log.trace(f\"Extracted {info} for evaluation:\\n{code}\")\n        else:\n            code = textwrap.dedent(RAW_CODE_REGEX.fullmatch(code).group(\"code\"))\n            log.trace(\n                f\"Eval message contains unformatted or badly formatted code, \"\n                f\"stripping whitespace only:\\n{code}\"\n            )\n\n        return code\n\n    @staticmethod\n    def get_results_message(results: dict) -> Tuple[str, str]:\n        \"\"\"Return a user-friendly message and error corresponding to the process's return code.\"\"\"\n        stdout, returncode = results[\"stdout\"], results[\"returncode\"]\n        msg = f\"Your eval job has completed with return code {returncode}\"\n        error = \"\"\n\n        if returncode is None:\n            msg = \"Your eval job has failed\"\n            error = stdout.strip()\n        elif returncode == 128 + Signals.SIGKILL:\n            msg = \"Your eval job timed out or ran out of memory\"\n        elif returncode == 255:\n            msg = \"Your eval job has failed\"\n            error = \"A fatal NsJail error occurred\"\n        else:\n            # Try to append signal's name if one exists\n            try:\n                name = Signals(returncode - 128).name\n                msg = f\"{msg} ({name})\"\n            except ValueError:\n                pass\n\n        return msg, error\n\n    async def format_output(self, output: str) -> Tuple[str, Optional[str]]:\n        \"\"\"\n        Format the output and return a tuple of the formatted output and a URL to the full output.\n\n        Prepend each line with a line number. Truncate if there are over 10 lines or 1000 characters\n        and upload the full output to a paste service.\n        \"\"\"\n        log.trace(\"Formatting output...\")\n\n        output = output.strip(\" \\n\")\n        original_output = output  # To be uploaded to a pasting service if needed\n        paste_link = None\n\n        if \"<@\" in output:\n            output = output.replace(\"<@\", \"<@\\u200B\")  # Zero-width space\n\n        if \"<!@\" in output:\n            output = output.replace(\"<!@\", \"<!@\\u200B\")  # Zero-width space\n\n        if ESCAPE_REGEX.findall(output):\n            return \"Code block escape attempt detected; will not output result\", paste_link\n\n        truncated = False\n        lines = output.count(\"\\n\")\n\n        if lines > 0:\n            output = output.split(\"\\n\")[:10]  # Only first 10 cause the rest is truncated anyway\n            output = (f\"{i:03d} | {line}\" for i, line in enumerate(output, 1))\n            output = \"\\n\".join(output)\n\n        if lines > 10:\n            truncated = True\n            if len(output) >= 1000:\n                output = f\"{output[:1000]}\\n... (truncated - too long, too many lines)\"\n            else:\n                output = f\"{output}\\n... (truncated - too many lines)\"\n        elif len(output) >= 1000:\n            truncated = True\n            output = f\"{output[:1000]}\\n... (truncated - too long)\"\n\n        if truncated:\n            paste_link = await self.upload_output(original_output)\n\n        output = output.strip()\n        if not output:\n            output = \"[No output]\"\n\n        return output, paste_link\n\n    @command(name=\"eval\", aliases=(\"e\",))\n    @guild_only()\n    @in_channel(Channels.bot, bypass_roles=EVAL_ROLES)\n    async def eval_command(self, ctx: Context, *, code: str = None) -> None:\n        \"\"\"\n        Run Python code and get the results.\n\n        This command supports multiple lines of code, including code wrapped inside a formatted code\n        block. We've done our best to make this safe, but do let us know if you manage to find an\n        issue with it!\n        \"\"\"\n        if ctx.author.id in self.jobs:\n            await ctx.send(\n                f\"{ctx.author.mention} You've already got a job running - \"\n                \"please wait for it to finish!\"\n            )\n            return\n\n        if not code:  # None or empty string\n            await ctx.invoke(self.bot.get_command(\"help\"), \"eval\")\n            return\n\n        log.info(f\"Received code from {ctx.author} for evaluation:\\n{code}\")\n\n        self.jobs[ctx.author.id] = datetime.datetime.now()\n        code = self.prepare_input(code)\n\n        try:\n            async with ctx.typing():\n                results = await self.post_eval(code)\n                msg, error = self.get_results_message(results)\n\n                if error:\n                    output, paste_link = error, None\n                else:\n                    output, paste_link = await self.format_output(results[\"stdout\"])\n\n                msg = f\"{ctx.author.mention} {msg}.\\n\\n```py\\n{output}\\n```\"\n                if paste_link:\n                    msg = f\"{msg}\\nFull output: {paste_link}\"\n\n                response = await ctx.send(msg)\n                self.bot.loop.create_task(\n                    wait_for_deletion(response, user_ids=(ctx.author.id,), client=ctx.bot)\n                )\n\n                log.info(f\"{ctx.author}'s job had a return code of {results['returncode']}\")\n        finally:\n            del self.jobs[ctx.author.id]\n\n\ndef setup(bot: Bot) -> None:\n    \"\"\"Snekbox cog load.\"\"\"\n    bot.add_cog(Snekbox(bot))\n    log.info(\"Cog loaded: Snekbox\")\n", "path": "bot/cogs/snekbox.py"}], "after_files": [{"content": "import datetime\nimport logging\nimport re\nimport textwrap\nfrom signal import Signals\nfrom typing import Optional, Tuple\n\nfrom discord.ext.commands import Bot, Cog, Context, command, guild_only\n\nfrom bot.constants import Channels, Roles, URLs\nfrom bot.decorators import in_channel\nfrom bot.utils.messages import wait_for_deletion\n\nlog = logging.getLogger(__name__)\n\nESCAPE_REGEX = re.compile(\"[`\\u202E\\u200B]{3,}\")\nFORMATTED_CODE_REGEX = re.compile(\n    r\"^\\s*\"                                 # any leading whitespace from the beginning of the string\n    r\"(?P<delim>(?P<block>```)|``?)\"        # code delimiter: 1-3 backticks; (?P=block) only matches if it's a block\n    r\"(?(block)(?:(?P<lang>[a-z]+)\\n)?)\"    # if we're in a block, match optional language (only letters plus newline)\n    r\"(?:[ \\t]*\\n)*\"                        # any blank (empty or tabs/spaces only) lines before the code\n    r\"(?P<code>.*?)\"                        # extract all code inside the markup\n    r\"\\s*\"                                  # any more whitespace before the end of the code markup\n    r\"(?P=delim)\"                           # match the exact same delimiter from the start again\n    r\"\\s*$\",                                # any trailing whitespace until the end of the string\n    re.DOTALL | re.IGNORECASE               # \".\" also matches newlines, case insensitive\n)\nRAW_CODE_REGEX = re.compile(\n    r\"^(?:[ \\t]*\\n)*\"                       # any blank (empty or tabs/spaces only) lines before the code\n    r\"(?P<code>.*?)\"                        # extract all the rest as code\n    r\"\\s*$\",                                # any trailing whitespace until the end of the string\n    re.DOTALL                               # \".\" also matches newlines\n)\n\nMAX_PASTE_LEN = 1000\nEVAL_ROLES = (Roles.helpers, Roles.moderator, Roles.admin, Roles.owner, Roles.rockstars, Roles.partners)\n\n\nclass Snekbox(Cog):\n    \"\"\"Safe evaluation of Python code using Snekbox.\"\"\"\n\n    def __init__(self, bot: Bot):\n        self.bot = bot\n        self.jobs = {}\n\n    async def post_eval(self, code: str) -> dict:\n        \"\"\"Send a POST request to the Snekbox API to evaluate code and return the results.\"\"\"\n        url = URLs.snekbox_eval_api\n        data = {\"input\": code}\n        async with self.bot.http_session.post(url, json=data, raise_for_status=True) as resp:\n            return await resp.json()\n\n    async def upload_output(self, output: str) -> Optional[str]:\n        \"\"\"Upload the eval output to a paste service and return a URL to it if successful.\"\"\"\n        log.trace(\"Uploading full output to paste service...\")\n\n        if len(output) > MAX_PASTE_LEN:\n            log.info(\"Full output is too long to upload\")\n            return \"too long to upload\"\n\n        url = URLs.paste_service.format(key=\"documents\")\n        try:\n            async with self.bot.http_session.post(url, data=output, raise_for_status=True) as resp:\n                data = await resp.json()\n\n            if \"key\" in data:\n                return URLs.paste_service.format(key=data[\"key\"])\n        except Exception:\n            # 400 (Bad Request) means there are too many characters\n            log.exception(\"Failed to upload full output to paste service!\")\n\n    @staticmethod\n    def prepare_input(code: str) -> str:\n        \"\"\"Extract code from the Markdown, format it, and insert it into the code template.\"\"\"\n        match = FORMATTED_CODE_REGEX.fullmatch(code)\n        if match:\n            code, block, lang, delim = match.group(\"code\", \"block\", \"lang\", \"delim\")\n            code = textwrap.dedent(code)\n            if block:\n                info = (f\"'{lang}' highlighted\" if lang else \"plain\") + \" code block\"\n            else:\n                info = f\"{delim}-enclosed inline code\"\n            log.trace(f\"Extracted {info} for evaluation:\\n{code}\")\n        else:\n            code = textwrap.dedent(RAW_CODE_REGEX.fullmatch(code).group(\"code\"))\n            log.trace(\n                f\"Eval message contains unformatted or badly formatted code, \"\n                f\"stripping whitespace only:\\n{code}\"\n            )\n\n        return code\n\n    @staticmethod\n    def get_results_message(results: dict) -> Tuple[str, str]:\n        \"\"\"Return a user-friendly message and error corresponding to the process's return code.\"\"\"\n        stdout, returncode = results[\"stdout\"], results[\"returncode\"]\n        msg = f\"Your eval job has completed with return code {returncode}\"\n        error = \"\"\n\n        if returncode is None:\n            msg = \"Your eval job has failed\"\n            error = stdout.strip()\n        elif returncode == 128 + Signals.SIGKILL:\n            msg = \"Your eval job timed out or ran out of memory\"\n        elif returncode == 255:\n            msg = \"Your eval job has failed\"\n            error = \"A fatal NsJail error occurred\"\n        else:\n            # Try to append signal's name if one exists\n            try:\n                name = Signals(returncode - 128).name\n                msg = f\"{msg} ({name})\"\n            except ValueError:\n                pass\n\n        return msg, error\n\n    @staticmethod\n    def get_status_emoji(results: dict) -> str:\n        \"\"\"Return an emoji corresponding to the status code or lack of output in result.\"\"\"\n        if not results[\"stdout\"].strip():  # No output\n            return \":warning:\"\n        elif results[\"returncode\"] == 0:  # No error\n            return \":white_check_mark:\"\n        else:  # Exception\n            return \":x:\"\n\n    async def format_output(self, output: str) -> Tuple[str, Optional[str]]:\n        \"\"\"\n        Format the output and return a tuple of the formatted output and a URL to the full output.\n\n        Prepend each line with a line number. Truncate if there are over 10 lines or 1000 characters\n        and upload the full output to a paste service.\n        \"\"\"\n        log.trace(\"Formatting output...\")\n\n        output = output.strip(\" \\n\")\n        original_output = output  # To be uploaded to a pasting service if needed\n        paste_link = None\n\n        if \"<@\" in output:\n            output = output.replace(\"<@\", \"<@\\u200B\")  # Zero-width space\n\n        if \"<!@\" in output:\n            output = output.replace(\"<!@\", \"<!@\\u200B\")  # Zero-width space\n\n        if ESCAPE_REGEX.findall(output):\n            return \"Code block escape attempt detected; will not output result\", paste_link\n\n        truncated = False\n        lines = output.count(\"\\n\")\n\n        if lines > 0:\n            output = output.split(\"\\n\")[:10]  # Only first 10 cause the rest is truncated anyway\n            output = (f\"{i:03d} | {line}\" for i, line in enumerate(output, 1))\n            output = \"\\n\".join(output)\n\n        if lines > 10:\n            truncated = True\n            if len(output) >= 1000:\n                output = f\"{output[:1000]}\\n... (truncated - too long, too many lines)\"\n            else:\n                output = f\"{output}\\n... (truncated - too many lines)\"\n        elif len(output) >= 1000:\n            truncated = True\n            output = f\"{output[:1000]}\\n... (truncated - too long)\"\n\n        if truncated:\n            paste_link = await self.upload_output(original_output)\n\n        output = output.strip()\n        if not output:\n            output = \"[No output]\"\n\n        return output, paste_link\n\n    @command(name=\"eval\", aliases=(\"e\",))\n    @guild_only()\n    @in_channel(Channels.bot, bypass_roles=EVAL_ROLES)\n    async def eval_command(self, ctx: Context, *, code: str = None) -> None:\n        \"\"\"\n        Run Python code and get the results.\n\n        This command supports multiple lines of code, including code wrapped inside a formatted code\n        block. We've done our best to make this safe, but do let us know if you manage to find an\n        issue with it!\n        \"\"\"\n        if ctx.author.id in self.jobs:\n            await ctx.send(\n                f\"{ctx.author.mention} You've already got a job running - \"\n                \"please wait for it to finish!\"\n            )\n            return\n\n        if not code:  # None or empty string\n            await ctx.invoke(self.bot.get_command(\"help\"), \"eval\")\n            return\n\n        log.info(f\"Received code from {ctx.author} for evaluation:\\n{code}\")\n\n        self.jobs[ctx.author.id] = datetime.datetime.now()\n        code = self.prepare_input(code)\n\n        try:\n            async with ctx.typing():\n                results = await self.post_eval(code)\n                msg, error = self.get_results_message(results)\n\n                if error:\n                    output, paste_link = error, None\n                else:\n                    output, paste_link = await self.format_output(results[\"stdout\"])\n\n                icon = self.get_status_emoji(results)\n                msg = f\"{ctx.author.mention} {icon} {msg}.\\n\\n```py\\n{output}\\n```\"\n                if paste_link:\n                    msg = f\"{msg}\\nFull output: {paste_link}\"\n\n                response = await ctx.send(msg)\n                self.bot.loop.create_task(\n                    wait_for_deletion(response, user_ids=(ctx.author.id,), client=ctx.bot)\n                )\n\n                log.info(f\"{ctx.author}'s job had a return code of {results['returncode']}\")\n        finally:\n            del self.jobs[ctx.author.id]\n\n\ndef setup(bot: Bot) -> None:\n    \"\"\"Snekbox cog load.\"\"\"\n    bot.add_cog(Snekbox(bot))\n    log.info(\"Cog loaded: Snekbox\")\n", "path": "bot/cogs/snekbox.py"}]}