Skip to content

Instantly share code, notes, and snippets.

@DarkblooM-IO
Last active June 5, 2024 20:34
Show Gist options
  • Save DarkblooM-IO/34d9d1a04a00b1a4f96329b919279884 to your computer and use it in GitHub Desktop.
Save DarkblooM-IO/34d9d1a04a00b1a4f96329b919279884 to your computer and use it in GitHub Desktop.
ASCIIMath to PNG Discord bot
import discord # discord.py==2.3.2
import matplotlib.pyplot as plt # matplotlib==3.9.0
from dotenv import load_dotenv # python-dotenv==1.0.1
from os import getenv, remove
from py_asciimath.translator.translator import ASCIIMath2Tex # py-asciimath==0.3.0
from discord.ext import commands
load_dotenv()
TOKEN: str = getenv("TOKEN") # stored in .env file
CMD_PREFIX: str = "!"
def ASCIIMath2PNG(expr: str, filename: str = "output.png") -> None:
parser = ASCIIMath2Tex(log=False, inplace=True)
output = "$"+parser.translate(expr.strip(), displaystyle=True, from_file=False, pprint=False)[2:-2]+"$"
fig = plt.figure(figsize=(3, 0.5))
text = fig.text(x=0.5, y=0.5, s=output, horizontalalignment="center", verticalalignment="center", fontsize=16)
plt.savefig(filename)
intents: discord.Intents = discord.Intents.default()
intents.message_content = True
bot: commands.Bot = commands.Bot(command_prefix=CMD_PREFIX, intents=intents)
@bot.event
async def on_ready() -> None:
print(f"Logged in as {bot.user}")
@bot.command(name="math")
async def cmd_math(ctx: commands.Context, *, expr: str) -> None:
async with ctx.channel.typing():
ASCIIMath2PNG(expr)
file = discord.File("./output.png")
await ctx.reply(file=file)
remove("./output.png")
print(len(expr))
@cmd_math.error
async def error_math(ctx: commands.Context, err) -> None:
if isinstance(err, commands.MissingRequiredArgument):
await ctx.reply("Usage: !math `[expression]`\n[Syntax](https://asciimath.org/)")
if __name__ == "__main__":
bot.run(TOKEN)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment