Skip to content

Commit 646008a

Browse files
authored
Merge pull request #219 from practical-python-org/latex_changes
bugfix/Update general_latex.py
2 parents 101a748 + ba891eb commit 646008a

File tree

1 file changed

+31
-7
lines changed

1 file changed

+31
-7
lines changed

src/zorak/cogs/general/general_latex.py

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,29 +18,53 @@ def __init__(self, bot):
1818
self.bot = bot
1919

2020
@commands.slash_command()
21-
async def latex(self, ctx, equation):
21+
async def latex(self, ctx, equation, *, bg_color = "black", txt_color = "white", dpi = 200):
2222
"""
2323
Sends a mathematical equation using an API and CairoSVG
2424
"""
2525
logger.info("%s used the %s command."
2626
, ctx.author.name
2727
, ctx.command)
2828

29-
escape_characters = {"\n": r"\n", "\r": r"\r", "\t": r"\t", "\x08": r"\b", "\x0c": r"\f", "\x0b": r"\v", "\x07": r"\a"}
29+
30+
# check for valid user specified color for text and background
31+
colors = [
32+
#bg and txt ok
33+
"black", "white", "red", "yellow", "green", "blue", "cyan", "magenta",
34+
#only bg ok
35+
"orange", "olive", "lime", "teal", "purple", "violet", "pink", "brown", "gray", "lightgray"
36+
]
37+
38+
bg_color = bg_color.replace(" ", "").lower()
39+
txt_color = txt_color.lower()
40+
41+
if bg_color not in colors:
42+
bg_color = "black"
43+
if txt_color not in colors[:8]:
44+
txt_color = "white"
45+
46+
# handle necessary character replacements
47+
escape_characters = {
48+
"\n": r"\n", "\r": r"\r",
49+
"\t": r"\t", "\x08": r"\b",
50+
"\x0c": r"\f", "\x0b": r"\v",
51+
"\x07": r"\a", " ": "&space;"
52+
}
3053

3154
for e, c in escape_characters.items():
3255
equation = equation.replace(e, c)
3356

34-
if " " in equation: # The URL errors when it contains spaces.
35-
await ctx.respond("Your equation may not contain spaces!")
36-
return
57+
# prevent user specified dpi from being too big
58+
dpi = max(int(dpi), 500)
59+
60+
image_path = r"https://latex.codecogs.com/png.image?\dpi{" + f"{dpi}" + \
61+
r"}\bg{" + bg_color + r"}\color{" + txt_color + "}" + equation
3762

38-
image_path = r"https://latex.codecogs.com/png.image?\dpi{200}\bg{black}\color{white}" + equation
3963
r = requests.get(image_path, timeout=5)
4064

4165
if r.status_code == 200:
4266

43-
embed = discord.Embed(title="LaTeX", description=equation)
67+
embed = discord.Embed(title="LaTeX", description=equation.replace("&space;", " "))
4468
embed.set_image(url=image_path) # Set the image in the embed
4569

4670
# Send the embed with the image

0 commit comments

Comments
 (0)