2025-05-14 20:27:49 -04:00
|
|
|
# context.py
|
|
|
|
|
|
|
|
|
|
import os
|
|
|
|
|
import yaml
|
|
|
|
|
import discord
|
|
|
|
|
|
|
|
|
|
base_dir = os.path.dirname(__file__)
|
|
|
|
|
with open(os.path.join(base_dir, "settings.yml"), "r", encoding="utf-8") as f:
|
|
|
|
|
settings = yaml.safe_load(f)
|
|
|
|
|
|
2025-09-20 15:36:13 -04:00
|
|
|
# Determine whether context should be included. Preference order:
|
|
|
|
|
# 1) `AI_INCLUDE_CONTEXT` environment variable if present
|
|
|
|
|
# 2) `settings.yml` -> context.enabled
|
|
|
|
|
env_val = os.getenv("AI_INCLUDE_CONTEXT", None)
|
|
|
|
|
if env_val is not None:
|
|
|
|
|
AI_INCLUDE_CONTEXT = str(env_val).lower() == "true"
|
|
|
|
|
else:
|
|
|
|
|
AI_INCLUDE_CONTEXT = settings.get("context", {}).get("enabled", True)
|
|
|
|
|
|
|
|
|
|
CONTEXT_LIMIT = settings.get("context", {}).get("max_messages", 15) if AI_INCLUDE_CONTEXT else 0
|
2025-05-14 20:27:49 -04:00
|
|
|
|
2025-06-06 15:05:03 -04:00
|
|
|
# Returns full discord.Message objects (for logic)
|
|
|
|
|
async def fetch_raw_context(channel, limit=CONTEXT_LIMIT):
|
2025-09-20 15:36:13 -04:00
|
|
|
# If context injection is disabled or limit is <= 0, return early.
|
|
|
|
|
if not AI_INCLUDE_CONTEXT or (not isinstance(limit, int)) or limit <= 0:
|
|
|
|
|
return []
|
|
|
|
|
|
2025-05-14 20:27:49 -04:00
|
|
|
messages = []
|
|
|
|
|
async for message in channel.history(limit=100):
|
|
|
|
|
# Skip other bots (but not Delta herself)
|
|
|
|
|
if message.author.bot and message.author.id != channel.guild.me.id:
|
|
|
|
|
continue
|
2025-06-06 15:05:03 -04:00
|
|
|
messages.append(message)
|
2025-05-14 20:27:49 -04:00
|
|
|
if len(messages) >= limit:
|
|
|
|
|
break
|
|
|
|
|
messages.reverse()
|
|
|
|
|
return messages
|
|
|
|
|
|
2025-06-06 15:05:03 -04:00
|
|
|
# Keeps your clean format logic for LLM
|
|
|
|
|
def format_context(messages: list[discord.Message]) -> str:
|
|
|
|
|
lines = []
|
|
|
|
|
for message in messages:
|
|
|
|
|
raw = message.clean_content
|
|
|
|
|
clean = raw.strip().replace("\n", " ").replace("\r", "")
|
|
|
|
|
clean = " ".join(clean.split())
|
|
|
|
|
if not clean or clean.startswith("!"):
|
|
|
|
|
continue
|
|
|
|
|
line = f"{message.created_at.strftime('%Y-%m-%d %H:%M')} - {message.author.display_name}: {clean}"
|
|
|
|
|
lines.append(line)
|
2025-05-14 20:27:49 -04:00
|
|
|
return "\n".join(lines)
|
2025-06-06 15:05:03 -04:00
|
|
|
|