Last active
March 11, 2025 17:19
-
-
Save DarkblooM-IO/34d9d1a04a00b1a4f96329b919279884 to your computer and use it in GitHub Desktop.
ASCIIMath to PNG Discord bot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
ASCIIMath to PNG Discord bot | |
Copyright (C) 2025 ÐarkbloøM | |
This program is free software: you can redistribute it and/or modify | |
it under the terms of the GNU General Public License as published by | |
the Free Software Foundation, either version 3 of the License, or | |
(at your option) any later version. | |
This program is distributed in the hope that it will be useful, | |
but WITHOUT ANY WARRANTY; without even the implied warranty of | |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
GNU General Public License for more details. | |
You should have received a copy of the GNU General Public License | |
along with this program. If not, see <https://www.gnu.org/licenses/>. | |
""" | |
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") | |
@cmd_math.error | |
async def error_math(ctx: commands.Context, err) -> None: | |
if isinstance(err, commands.MissingRequiredArgument): | |
await ctx.reply(f"Usage: {CMD_PREFIX}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