Files
background.js
bot.py
content.css
content.js
manifest.json
popup.css
popup.html
popup.js
requirements.txt
Code
9 588
bot.py
import asyncio
import logging
import os
import aiohttp
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO)
bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())
@bot.event
async def on_ready():
for guild in bot.guilds:
try:
bot.tree.copy_global_to(guild=guild)
synced = await bot.tree.sync(guild=guild)
logging.info("Synced %d application commands to %s", len(synced), guild.name)
except Exception:
logging.exception("Failed to sync application commands to %s", guild.name)
logging.info("Logged in as %s", bot.user)
print("KODARI_READY", flush=True)
@bot.tree.command(name="test_embed", description="Show a sample embed with fictional test data")
async def test_embed(interaction: discord.Interaction):
embed = discord.Embed(
title="Test Submission",
description="Example only — no personal information or password was collected.",
color=discord.Color.blurple(),
)
embed.add_field(name="Email", value="demo@example.test", inline=False)
embed.add_field(name="School", value="Example School", inline=False)
embed.add_field(name="Password", value="Not collected", inline=False)
await interaction.response.send_message(embed=embed, ephemeral=True)
class MockLoginModal(discord.ui.Modal, title="Sparx Demo Login"):
email = discord.ui.TextInput(
label="Demo school email",
placeholder="student@school.example.test",
max_length=100,
)
password = discord.ui.TextInput(
label="Demo password (never use a real one)",
placeholder="DemoPass123!",
style=discord.TextStyle.short,
max_length=64,
)
async def on_submit(self, interaction: discord.Interaction):
if (
self.email.value != "student@school.example.test"
or self.password.value != "DemoPass123!"
):
await interaction.response.send_message(
"Demo only: use `student@school.example.test` and `DemoPass123!`. "
"Do not enter real account details.",
ephemeral=True,
)
return
embed = discord.Embed(
title="Mock Login Successful",
description="This was a local demo only. No credentials were saved and Sparx was not contacted.",
color=discord.Color.green(),
)
embed.add_field(name="Email", value="student@school.example.test", inline=False)
embed.add_field(name="Password", value="Not displayed", inline=False)
await interaction.response.send_message(embed=embed, ephemeral=True)
@bot.tree.command(name="mock_login", description="Try a fake-only Sparx login simulation")
async def mock_login(interaction: discord.Interaction):
await interaction.response.send_modal(MockLoginModal())
@bot.tree.command(
name="tutor",
description="Get a worked AI answer to your question(s)",
)
@discord.app_commands.describe(
question="The question or questions you want answered",
attempt="Optional work or context to consider",
)
async def tutor(
interaction: discord.Interaction,
question: str,
attempt: str = "",
):
api_url = os.getenv("TUTOR_API_URL")
api_key = os.getenv("TUTOR_API_KEY")
model = os.getenv("TUTOR_MODEL")
if not api_url or not api_key or not model:
await interaction.response.send_message(
"Tutor AI is not configured yet. Set `TUTOR_API_URL`, `TUTOR_API_KEY`, "
"and `TUTOR_MODEL` in the bot environment, then restart it.",
ephemeral=True,
)
return
await interaction.response.defer(ephemeral=True, thinking=True)
payload = {
"model": model,
"messages": [
{
"role": "system",
"content": (
"Answer every question the user included. Give a clear, accurate worked "
"solution for each one, show the reasoning step by step, and state the "
"final answer explicitly. If the prompt is ambiguous or missing essential "
"information, say what needs clarification rather than guessing. Never ask "
"for passwords or personal account details."
),
},
{
"role": "user",
"content": (
f"Question(s): {question}\n"
f"Student's attempt: {attempt or 'Not provided'}"
),
},
],
}
try:
timeout = aiohttp.ClientTimeout(total=30)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.post(
api_url,
headers={"Authorization": f"Bearer {api_key}"},
json=payload,
) as response:
if response.status >= 400:
logging.warning("Tutor API returned HTTP %s", response.status)
await interaction.edit_original_response(
content="The tutor service returned an error. Check its settings and try again."
)
return
result = await response.json(content_type=None)
answer = result["choices"][0]["message"]["content"]
if not isinstance(answer, str) or not answer.strip():
raise ValueError("Tutor API returned no text")
answer = answer.strip()
answer_chunks = [answer[index:index + 1900] for index in range(0, len(answer), 1900)]
await interaction.edit_original_response(
content=answer_chunks[0]
)
for chunk in answer_chunks[1:]:
await interaction.followup.send(chunk, ephemeral=True)
except (aiohttp.ClientError, asyncio.TimeoutError, KeyError, IndexError, TypeError, ValueError):
logging.exception("Tutor request failed")
await interaction.edit_original_response(
content="I couldn't get a tutoring response right now. Check the tutor service settings and try again."
)
if __name__ == "__main__":
token = os.getenv("DISCORD_TOKEN")
if not token or token == "your_discord_bot_token_here":
raise SystemExit("Set DISCORD_TOKEN in .env to your Discord bot token.")
bot.run(token)