No chat to show

This project's files are all here to explore.

Files
bot.py
requirements.txt
Code
2 185
bot.py
import ast
import logging
import math
import os
import random

import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv


logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("math_tutor")

load_dotenv()

bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())


class MathInputError(ValueError):
    pass


def _linear_form(node):
    if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) and not isinstance(node.value, bool):
        value = float(node.value)
        if math.isfinite(value):
            return 0.0, value
        raise MathInputError("Use finite numbers only.")

    if isinstance(node, ast.Name) and node.id == "x":
        return 1.0, 0.0

    if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
        coefficient, constant = _linear_form(node.operand)
        sign = -1.0 if isinstance(node.op, ast.USub) else 1.0
        return sign * coefficient, sign * constant

    if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub)):
        left_a, left_b = _linear_form(node.left)
        right_a, right_b = _linear_form(node.right)
        sign = -1.0 if isinstance(node.op, ast.Sub) else 1.0
        return left_a + sign * right_a, left_b + sign * right_b

    if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mult):
        left_a, left_b = _linear_form(node.left)
        right_a, right_b = _linear_form(node.right)
        if left_a and right_a:
            raise MathInputError("Only linear equations are supported; products of x terms are not linear.")
        if left_a:
            return left_a * right_b, left_b * right_b
        if right_a:
            return right_a * left_b, right_b * left_b
        return 0.0, left_b * right_b

    if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Div):
        numerator_a, numerator_b = _linear_form(node.left)
        denominator_a, denominator_b = _linear_form(node.right)
        if denominator_a:
            raise MathInputError("The denominator must be a non-zero constant.")
        if math.isclose(denominator_b, 0.0, abs_tol=1e-12):
            raise MathInputError("Division by zero is not allowed.")
        return numerator_a / denominator_b, numerator_b / denominator_b

    raise MathInputError("Use a linear equation with x and the operators +, -, *, and /.")


def _equation_solution(equation):
    if len(equation) > 100 or equation.count("=") != 1:
        raise MathInputError("Enter one equation, such as `2*x + 3 = 11` (up to 100 characters).")

    left_text, right_text = equation.split("=", 1)
    try:
        left_tree = ast.parse(left_text.strip(), mode="eval")
        right_tree = ast.parse(right_text.strip(), mode="eval")
    except SyntaxError as exc:
        raise MathInputError("I couldn't read that equation. Try `2*x + 3 = 11`.") from exc

    if len(list(ast.walk(left_tree))) + len(list(ast.walk(right_tree))) > 64:
        raise MathInputError("That equation is too long to check.")

    left_a, left_b = _linear_form(left_tree.body)
    right_a, right_b = _linear_form(right_tree.body)
    coefficient = left_a - right_a
    constant = right_b - left_b

    if math.isclose(coefficient, 0.0, abs_tol=1e-12):
        raise MathInputError("That equation does not have one unique value for x.")

    answer = constant / coefficient
    if not math.isfinite(answer):
        raise MathInputError("That equation's solution is outside the range I can check.")
    return answer


@bot.event
async def on_ready():
    try:
        await bot.tree.sync()
    except discord.HTTPException:
        logger.exception("Could not sync slash commands")
    logger.info("Logged in as %s", bot.user)
    print("KODARI_READY", flush=True)


@bot.tree.command(name="hint", description="Get a guided hint for a linear equation")
@app_commands.describe(equation="A linear equation, for example 2*x + 3 = 11")
@app_commands.checks.cooldown(2, 10.0)
async def hint(interaction: discord.Interaction, equation: str):
    try:
        _equation_solution(equation)
    except MathInputError as exc:
        await interaction.response.send_message(str(exc), ephemeral=True)
        return

    await interaction.response.send_message(
        "This is a linear equation. Collect the x terms on one side and the constants on the other. "
        "Then use inverse operations on both sides to isolate x. What would you try first?",
        ephemeral=True,
    )


@bot.tree.command(name="check", description="Check your attempted answer to a linear equation")
@app_commands.describe(
    equation="A linear equation, for example 2*x + 3 = 11",
    answer="Your attempted value for x",
)
@app_commands.checks.cooldown(3, 10.0)
async def check(interaction: discord.Interaction, equation: str, answer: str):
    try:
        expected = _equation_solution(equation)
        attempt = float(answer.strip())
        if not math.isfinite(attempt):
            raise ValueError
    except MathInputError as exc:
        await interaction.response.send_message(str(exc), ephemeral=True)
        return
    except ValueError:
        await interaction.response.send_message("Enter your answer as a number, such as `4` or `-2.5`.", ephemeral=True)
        return

    if math.isclose(attempt, expected, rel_tol=1e-9, abs_tol=1e-9):
        message = "That's correct! Nice work."
    else:
        message = "Not quite. Check by substituting your value for x, then review the inverse operations you used. Try `/hint` for a nudge."
    await interaction.response.send_message(message, ephemeral=True)


@bot.tree.command(name="practice", description="Get a new linear equation to practise")
@app_commands.checks.cooldown(2, 10.0)
async def practice(interaction: discord.Interaction):
    coefficient = random.choice([value for value in range(-9, 10) if value != 0])
    answer = random.randint(-12, 12)
    constant = random.randint(-15, 15)
    result = coefficient * answer + constant
    sign = "+" if constant >= 0 else "-"
    equation = f"{coefficient}*x {sign} {abs(constant)} = {result}"
    await interaction.response.send_message(
        f"Solve this one: `{equation}`. When you're ready, use `/check` with your answer.",
        ephemeral=True,
    )


@bot.tree.error
async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
    if isinstance(error, app_commands.CommandOnCooldown):
        message = f"Please wait {error.retry_after:.1f} seconds before trying that again."
    else:
        logger.error("Slash command failed", exc_info=(type(error), error, error.__traceback__))
        message = "Something went wrong while handling that command. Please try again."

    if interaction.response.is_done():
        await interaction.followup.send(message, ephemeral=True)
    else:
        await interaction.response.send_message(message, ephemeral=True)


token = os.getenv("DISCORD_TOKEN")
if not token:
    raise RuntimeError("DISCORD_TOKEN is missing. Add it to your .env file.")

bot.run(token)