Files
bot.py
requirements.txt
Code
2 211
bot.py
import json
import logging
import os
from pathlib import Path
import discord
from discord import app_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("quest_solver")
QUESTS_FILE = Path(__file__).with_name("quests.json")
def load_quests():
if not QUESTS_FILE.exists():
return {}
with QUESTS_FILE.open("r", encoding="utf-8") as file:
quests = json.load(file)
if not isinstance(quests, dict):
raise ValueError("quests.json must contain a JSON object")
return quests
def save_quests(quests):
temporary_file = QUESTS_FILE.with_suffix(".json.tmp")
with temporary_file.open("w", encoding="utf-8") as file:
json.dump(quests, file, ensure_ascii=False, indent=2)
os.replace(temporary_file, QUESTS_FILE)
def quest_key(game, title):
return f"{game.strip().casefold()}::{title.strip().casefold()}"
def find_quest(game, title):
exact = QUESTS.get(quest_key(game, title))
if exact:
return exact, []
game_key = game.strip().casefold()
title_key = title.strip().casefold()
matches = [
quest for quest in QUESTS.values()
if quest.get("game", "").casefold() == game_key
and (title_key in quest.get("title", "").casefold()
or quest.get("title", "").casefold() in title_key)
]
return None, matches[:3]
QUESTS = load_quests()
class QuestSolverBot(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
await self.tree.sync()
logger.info("Slash commands synced")
bot = QuestSolverBot()
@bot.event
async def on_ready():
logger.info("Connected as %s", bot.user)
print("KODARI_READY", flush=True)
@bot.tree.command(name="solve", description="Look up a saved solution for a game quest")
@app_commands.describe(game="Game name", quest="Quest title")
async def solve(interaction: discord.Interaction, game: str, quest: str):
result, suggestions = find_quest(game, quest)
if result is None:
message = "I couldn't find that quest. Add it with `/add_quest`."
if suggestions:
message += " Similar quests: " + ", ".join(
f"{item['game']} — {item['title']}" for item in suggestions
)
await interaction.response.send_message(message, ephemeral=True)
return
embed = discord.Embed(
title=result["title"],
description=result["solution"],
color=discord.Color.green(),
)
embed.set_author(name=result["game"])
await interaction.response.send_message(embed=embed)
@bot.tree.command(name="hint", description="Get a hint for a saved game quest")
@app_commands.describe(game="Game name", quest="Quest title")
async def hint(interaction: discord.Interaction, game: str, quest: str):
result, suggestions = find_quest(game, quest)
if result is None:
message = "I couldn't find that quest. Add it with `/add_quest`."
if suggestions:
message += " Similar quests: " + ", ".join(
f"{item['game']} — {item['title']}" for item in suggestions
)
await interaction.response.send_message(message, ephemeral=True)
return
hints = result.get("hints", [])
if not hints:
await interaction.response.send_message(
"No hint has been added for that quest yet.", ephemeral=True
)
return
await interaction.response.send_message(
f"**{result['title']} — hint:** {hints[0]}", ephemeral=True
)
@bot.tree.command(name="add_quest", description="Add or update a quest solution")
@app_commands.describe(
game="Game name",
quest="Quest title",
solution="Walkthrough or solution",
hints="Optional hints separated with |",
)
@app_commands.checks.has_permissions(manage_guild=True)
async def add_quest(
interaction: discord.Interaction,
game: str,
quest: str,
solution: str,
hints: str = "",
):
cleaned_game = game.strip()
cleaned_title = quest.strip()
entry = {
"game": cleaned_game,
"title": cleaned_title,
"solution": solution.strip(),
"hints": [hint_text.strip() for hint_text in hints.split("|") if hint_text.strip()],
}
QUESTS[quest_key(cleaned_game, cleaned_title)] = entry
save_quests(QUESTS)
await interaction.response.send_message(
f"Saved **{cleaned_title}** for **{cleaned_game}**.", ephemeral=True
)
@bot.tree.command(name="remove_quest", description="Remove a saved quest")
@app_commands.describe(game="Game name", quest="Quest title")
@app_commands.checks.has_permissions(manage_guild=True)
async def remove_quest(interaction: discord.Interaction, game: str, quest: str):
key = quest_key(game, quest)
removed = QUESTS.pop(key, None)
if removed is None:
await interaction.response.send_message("That quest isn't in the library.", ephemeral=True)
return
save_quests(QUESTS)
await interaction.response.send_message(
f"Removed **{removed['title']}** for **{removed['game']}**.", ephemeral=True
)
@bot.tree.command(name="quests", description="Browse saved quests")
@app_commands.describe(game="Optionally show quests for one game")
async def quests(interaction: discord.Interaction, game: str = ""):
entries = sorted(
(
entry for entry in QUESTS.values()
if not game.strip() or entry.get("game", "").casefold() == game.strip().casefold()
),
key=lambda entry: (entry.get("game", "").casefold(), entry.get("title", "").casefold()),
)
if not entries:
await interaction.response.send_message("No quests are saved yet.", ephemeral=True)
return
displayed = entries[:25]
description = "\n".join(f"**{entry['game']}** — {entry['title']}" for entry in displayed)
if len(entries) > len(displayed):
description += f"\n…and {len(entries) - len(displayed)} more."
embed = discord.Embed(title="Quest library", description=description, color=discord.Color.blurple())
await interaction.response.send_message(embed=embed, ephemeral=True)
@bot.tree.error
async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.MissingPermissions):
message = "You need the **Manage Server** permission to edit the quest library."
else:
logger.exception("Slash command failed", exc_info=error)
message = "Something went wrong while handling that command. Please try again."
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)