-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathblurple_formatter.py
70 lines (57 loc) · 2.54 KB
/
blurple_formatter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import asyncio
import traceback
import discord
from discord.ext import commands
from pydis_core.utils.logging import get_logger
from pydis_core.utils.paste_service import PasteFile, PasteTooLongError, PasteUploadError, send_to_paste_service
from pydis_core.utils.regex import FORMATTED_CODE_REGEX
from bot.bot import SirRobin
from bot.utils import blurple_formatter
logger = get_logger()
class BlurpleFormatter(commands.Cog):
"""Format code in accordance with PEP 9001."""
def __init__(self, bot: SirRobin):
self.bot = bot
self.lock = asyncio.Lock()
@staticmethod
def _format_code(code: str) -> str:
blurpified = blurple_formatter.blurplify(code)
blurpified = blurpified.replace("`", "`\u200d")
return blurpified
@commands.command(aliases=["blurp", "blurpify", "format"])
async def blurplify(self, ctx: commands.Context, *, code: str) -> None:
"""Format code in accordance with PEP 9001."""
if match := FORMATTED_CODE_REGEX.match(code):
code = match.group("code")
try:
async with self.lock:
blurpified = await asyncio.to_thread(self._format_code, code)
except SyntaxError as e:
err_info = "".join(traceback.format_exception_only(type(e), e)).replace("`", "`\u200d")
embed = discord.Embed(
title="Invalid Syntax!",
description=f"```\n{err_info}\n```",
color=0xCD6D6D,
)
await ctx.send(embed=embed, allowed_mentions=discord.AllowedMentions.none())
return
if len(blurpified) > 2000:
paste_file = PasteFile(content=blurpified)
try:
paste = await send_to_paste_service(
files=[paste_file],
http_session=self.bot.http_session,
)
except PasteUploadError:
logger.exception("Generic upload error from paste service:")
await ctx.send(":warning: Failed to upload full output")
return
except PasteTooLongError:
await ctx.send(":warning: Failed to upload full output, too long for paste service.")
return
await ctx.send(f":white_check_mark: Formatted code too big, full output: {paste.link}")
return
await ctx.send(f"```py\n{blurpified}\n```", allowed_mentions=discord.AllowedMentions.none())
async def setup(bot: SirRobin) -> None:
"""Load the BlurpleFormatter cog."""
await bot.add_cog(BlurpleFormatter(bot))