Files
bot.py
requirements.txt
Code
2 100
bot.py
import logging
import os
import aiohttp
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("homework_bot")
TOKEN = os.getenv("DISCORD_TOKEN")
API_KEY = os.getenv("OPENAI_API_KEY")
MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
class HomeworkBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix="!", intents=discord.Intents.default())
self.session = None
async def setup_hook(self):
self.session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=60))
await self.tree.sync()
async def close(self):
if self.session is not None:
await self.session.close()
await super().close()
bot = HomeworkBot()
@bot.event
async def on_ready():
logger.info("Logged in as %s", bot.user)
print("KODARI_READY", flush=True)
@bot.tree.command(name="homework", description="Get help answering a homework question")
@app_commands.describe(question="Your homework question (include relevant details)")
@app_commands.checks.cooldown(2, 30.0, key=lambda interaction: interaction.user.id)
async def homework(interaction: discord.Interaction, question: app_commands.Range[str, 1, 2000]):
await interaction.response.defer(ephemeral=True, thinking=True)
payload = {
"model": MODEL,
"messages": [
{"role": "system", "content": "Help the student answer their homework question. Give a clear answer and explain the steps or reasoning so they can learn. If information is missing, ask for it. Keep the response concise."},
{"role": "user", "content": question},
],
"max_tokens": 800,
}
try:
async with bot.session.post(
"https://api.openai.com/v1/chat/completions",
headers={"Authorization": f"Bearer {API_KEY}"},
json=payload,
) as response:
if response.status != 200:
logger.error("AI API request failed with status %s", response.status)
await interaction.followup.send("The AI service couldn't answer right now. Please try again later.", ephemeral=True)
return
data = await response.json()
answer = data["choices"][0]["message"]["content"]
if not isinstance(answer, str) or not answer.strip():
raise ValueError("Empty AI response")
while answer:
chunk = answer[:1900]
answer = answer[1900:]
await interaction.followup.send(chunk, ephemeral=True, allowed_mentions=discord.AllowedMentions.none())
except (aiohttp.ClientError, TimeoutError, KeyError, IndexError, TypeError, ValueError):
logger.exception("Could not answer homework question")
await interaction.followup.send("Something went wrong while generating an answer. Please try again.", 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:.0f} seconds before asking again."
else:
logger.error("Slash command failed: %s", error)
message = "Something went wrong. Please try again."
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
if __name__ == "__main__":
if not TOKEN or TOKEN == "your_discord_bot_token_here":
raise SystemExit("Set DISCORD_TOKEN in .env before starting the bot.")
if not API_KEY or API_KEY == "your_openai_api_key_here":
raise SystemExit("Set OPENAI_API_KEY in .env before starting the bot.")
bot.run(TOKEN, log_handler=None)