Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 298
bot.py
import asyncio
import logging
import os
import time
from collections import defaultdict, deque
from typing import Deque, Dict, List, Tuple
import discord
import httpx
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("ai-assistant")
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
AI_API_KEY = os.getenv("AI_API_KEY")
AI_API_URL = os.getenv("AI_API_URL", "https://api.openai.com/v1/chat/completions")
AI_MODEL = os.getenv("AI_MODEL", "gpt-4o-mini")
MAX_REQUESTS = int(os.getenv("MAX_REQUESTS_PER_MINUTE", "5"))
SYSTEM_PROMPT = os.getenv(
"SYSTEM_PROMPT",
"You are a helpful, concise AI assistant in a Discord server. "
"Use Markdown when it improves readability and never claim to have performed "
"actions you cannot perform.",
)
class RateLimitError(Exception):
"""Raised when a user has exceeded the assistant request limit."""
class AssistantService:
def __init__(self) -> None:
self.histories: Dict[Tuple[int, int, int], List[dict]] = defaultdict(list)
self.requests: Dict[int, Deque[float]] = defaultdict(deque)
self.client = httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=10.0))
self.lock = asyncio.Lock()
async def close(self) -> None:
await self.client.aclose()
def _check_rate_limit(self, user_id: int) -> None:
now = time.monotonic()
request_times = self.requests[user_id]
while request_times and now - request_times[0] >= 60:
request_times.popleft()
if len(request_times) >= MAX_REQUESTS:
retry_after = int(60 - (now - request_times[0])) + 1
raise RateLimitError(f"Please wait about {retry_after} seconds before trying again.")
request_times.append(now)
async def ask(self, key: Tuple[int, int, int], user_id: int, prompt: str) -> str:
prompt = prompt.strip()
if not prompt:
raise ValueError("Please provide a question.")
async with self.lock:
self._check_rate_limit(user_id)
history = self.histories[key]
messages = [{"role": "system", "content": SYSTEM_PROMPT}, *history]
messages.append({"role": "user", "content": prompt})
response = await self.client.post(
AI_API_URL,
headers={
"Authorization": f"Bearer {AI_API_KEY}",
"Content-Type": "application/json",
},
json={
"model": AI_MODEL,
"messages": messages,
"temperature": 0.7,
},
)
if response.status_code >= 400:
logger.error("AI API returned %s: %s", response.status_code, response.text[:500])
raise RuntimeError("The AI service rejected the request. Please try again later.")
try:
data = response.json()
answer = data["choices"][0]["message"]["content"].strip()
except (KeyError, IndexError, TypeError, AttributeError, ValueError) as error:
logger.exception("Unexpected AI API response")
raise RuntimeError("The AI service returned an invalid response.") from error
if not answer:
raise RuntimeError("The AI service returned an empty response.")
history.extend(
[
{"role": "user", "content": prompt},
{"role": "assistant", "content": answer},
]
)
del history[:-12]
return answer
def reset(self, key: Tuple[int, int, int]) -> None:
self.histories.pop(key, None)
class AssistantBot(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix="!", intents=intents, help_command=None)
self.assistant = AssistantService()
self.synced = False
async def setup_hook(self) -> None:
if not self.synced:
await self.tree.sync()
self.synced = True
logger.info("Application commands synced")
async def close(self) -> None:
await self.assistant.close()
await super().close()
bot = AssistantBot()
def conversation_key(channel: discord.abc.Messageable, user_id: int) -> Tuple[int, int, int]:
guild_id = getattr(getattr(channel, "guild", None), "id", 0) or 0
channel_id = getattr(channel, "id", 0) or 0
return guild_id, channel_id, user_id
async def answer_in_channel(
destination: discord.abc.Messageable,
user_id: int,
prompt: str,
) -> None:
try:
answer = await bot.assistant.ask(
conversation_key(destination, user_id),
user_id,
prompt,
)
except RateLimitError as error:
await destination.send(str(error), allowed_mentions=discord.AllowedMentions.none())
return
except ValueError as error:
await destination.send(str(error), allowed_mentions=discord.AllowedMentions.none())
return
except (httpx.HTTPError, RuntimeError):
logger.exception("Assistant request failed")
await destination.send(
"I couldn't complete that request right now. Please try again shortly.",
allowed_mentions=discord.AllowedMentions.none(),
)
return
for start in range(0, len(answer), 1900):
await destination.send(
answer[start : start + 1900],
allowed_mentions=discord.AllowedMentions.none(),
)
@bot.tree.command(name="ask", description="Ask the AI assistant a question")
@app_commands.describe(question="The question or request for the assistant")
async def ask_command(interaction: discord.Interaction, question: str) -> None:
await interaction.response.defer()
try:
answer = await bot.assistant.ask(
conversation_key(interaction.channel, interaction.user.id),
interaction.user.id,
question,
)
for start in range(0, len(answer), 1900):
await interaction.followup.send(
answer[start : start + 1900],
allowed_mentions=discord.AllowedMentions.none(),
)
except RateLimitError as error:
await interaction.followup.send(str(error), ephemeral=True)
except ValueError as error:
await interaction.followup.send(str(error), ephemeral=True)
except (httpx.HTTPError, RuntimeError):
logger.exception("Slash command request failed")
await interaction.followup.send(
"I couldn't complete that request right now. Please try again shortly.",
ephemeral=True,