Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 675
bot.py
import asyncio
import logging
import os
import re
import time
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Optional
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("zyroai")
BLUE = discord.Color.from_rgb(45, 126, 245)
GREEN = discord.Color.from_rgb(46, 204, 113)
ORANGE = discord.Color.from_rgb(243, 156, 18)
RED = discord.Color.from_rgb(231, 76, 60)
def format_seconds(seconds: int) -> str:
seconds = max(0, int(seconds))
minutes, seconds = divmod(seconds, 60)
if minutes:
return f"{minutes}m {seconds:02d}s"
return f"{seconds}s"
def progress_bar(percent: int, width: int = 10) -> str:
filled = round(max(0, min(100, percent)) / 100 * width)
return "โฐ" * filled + "โฑ" * (width - filled)
@dataclass(frozen=True)
class Homework:
key: str
name: str
due: str
questions: tuple[str, ...]
status: str
@dataclass
class QueueEntry:
user_id: int
homework: Homework
group_name: Optional[str] = None
created_at: float = field(default_factory=time.time)
@dataclass
class Session:
user_id: int
homework: Homework
difficulty: str
explanation_style: str
question_time: int
completed: int = 0
status: str = "Starting"
paused: bool = False
started_at: float = field(default_factory=time.time)
dm_message: Optional[discord.Message] = None
class ZyroBot(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
super().__init__(command_prefix="!", intents=intents, help_command=None)
self.log_channel_id = self._optional_int("ZYRO_LOG_CHANNEL_ID")
self.homeworks = [
Homework(
"maths-1",
"Algebra foundations",
"Tomorrow at 18:00",
(
"Simplify an algebraic expression",
"Solve a one-step equation",
"Solve a two-step equation",
"Check a solution by substitution",
"Explain the inverse operation used",
"Reflect on the method",
),
"In progress",
),
Homework(
"science-1",
"Forces and motion",
"Friday at 16:30",
(
"Identify the forces in a diagram",
"Calculate resultant force",
"Use the force equation",
"Compare two motion scenarios",
"Explain a unit conversion",
"Summarise the result",
),
"Not started",
),
Homework(
"english-1",
"Persuasive writing",
"Next Monday at 09:00",
(
"Identify the target audience",
"Choose a clear argument",
"Find supporting evidence",
"Write a counterargument",
"Improve word choice",
"Proofread the conclusion",
),
"Not started",
),
]
self.queue: list[QueueEntry] = []
self.sessions: dict[int, Session] = {}
self.session_tasks: dict[int, asyncio.Task] = {}
self.user_settings: dict[int, dict[str, str | int]] = defaultdict(
lambda: {
"question_time": 30,
"difficulty": "Standard",
"explanation": "Step by step",
"progress": "Detailed",
}
)
self.history: dict[int, list[str]] = defaultdict(list)
@staticmethod
def _optional_int(name: str) -> Optional[int]:
value = os.getenv(name, "").strip()
return int(value) if value.isdigit() else None
async def setup_hook(self) -> None:
await self.tree.sync()
def settings_for(self, user_id: int) -> dict[str, str | int]:
return self.user_settings[user_id]
def find_homework(self, key: str) -> Homework:
return next(homework for homework in self.homeworks if homework.key == key)
async def audit(self, event: str, user_id: int) -> None:
"""Write only non-sensitive operational events to the optional audit channel."""
if not self.log_channel_id:
return
try:
channel = self.get_channel(self.log_channel_id)
if channel is None:
channel = await self.fetch_channel(self.log_channel_id)
if isinstance(channel, discord.abc.Messageable):
embed = discord.Embed(title="ZyroAI audit event", color=BLUE)
embed.add_field(name="Event", value=event, inline=True)
embed.add_field(name="Discord user ID", value=str(user_id), inline=True)
await channel.send(embed=embed)
except (discord.DiscordException, OSError):
logger.exception("Could not write audit event")
def queue_position(self, user_id: int) -> Optional[int]:
for position, entry in enumerate(self.queue, 1):
if entry.user_id == user_id:
return position
return None
def queue_embed(self, user_id: int) -> discord.Embed:
position = self.queue_position(user_id)
session = self.sessions.get(user_id)
if session:
embed = discord.Embed(title="๐๏ธ Your task is in progress", color=BLUE)
embed.add_field(name="Homework", value=session.homework.name, inline=False)
embed.add_field(name="Status", value=session.status, inline=True)
embed.add_field(name="Progress", value=f"{session.completed}/{len(session.homework.questions)}", inline=True)
return embed
if position:
wait = format_seconds((position - 1) * 30)
embed = discord.Embed(title="๐๏ธ Your task is queued", color=ORANGE)
entry = self.queue[position - 1]
embed.add_field(name="Queue position", value=f"#{position}", inline=True)
embed.add_field(name="Users ahead", value=str(position - 1), inline=True)
embed.add_field(name="Estimated wait", value=wait, inline=True)
embed.add_field(name="Homework", value=entry.homework.name, inline=False)
embed.set_footer(text="ZyroAI will DM you when your learning session starts.")
return embed
return discord.Embed(title="No active queue task", description="Choose a homework assignment to join the queue.", color=BLUE)
async def enqueue(self, user_id: int, homework: Homework, group_name: Optional[str] = None) -> bool:
if user_id in self.sessions or any(entry.user_id == user_id for entry in self.queue):
return False
self.queue.append(QueueEntry(user_id, homework, group_name))
await self.audit("Queue joined", user_id)
asyncio.create_task(self.start_next())
return True
async def start_next(self) -> None:
if self.sessions or not self.queue: