Moiz

make discord bot ai reply liekreply you answer all

Kodari AI
KodariNov 13 at 7:12 pm 1
AIReplierBot
A Discord bot that automatically generates and posts AI-powered replies to user messages. It listens to server conversations, uses a language model to craft contextual responses, and sends them as replies. Features include configurable trigger keywords, cooldown settings, and an optional mention-only mode. The bot supports custom prompts per channel and logs all generated replies for moderation. Built with discord.py and an AI API integration, it provides a seamless, intelligent conversational experience for community engagement.
  • Create a discord.py bot that sends every non-bot text message to an AI chat API and replies in the same channel.

  • Keep short per-channel conversation context and serialize requests to avoid dropped or out-of-order replies.

  • Add dependency and .env templates; the bot needs Discord’s Message Content privileged intent enabled.

Created a Discord bot that sends every non-bot text message to an AI chat API and replies in the channel, keeping short conversation context per channel.

Set DISCORD_TOKEN and AI_API_KEY in .env. In the Discord Developer Portal, enable Message Content Intent under Bot → Privileged Gateway Intents or the bot won’t receive message text. Install dependencies with pip install -r requirements.txt, then run python bot.py.

Kodari can make mistakes. Review important code before using.
Files
bot.py
requirements.txt
Code
2 153
bot.py
import asyncio
import logging
import os
from collections import defaultdict

import aiohttp
import discord
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_reply_bot")

DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
AI_API_KEY = os.getenv("AI_API_KEY")
AI_BASE_URL = os.getenv("AI_BASE_URL", "https://api.openai.com/v1").rstrip("/")
AI_MODEL = os.getenv("AI_MODEL", "gpt-4o-mini")
SYSTEM_PROMPT = os.getenv(
    "AI_SYSTEM_PROMPT",
    "You are a helpful, friendly assistant in a Discord server. Answer the user's message directly and clearly.",
)
MAX_HISTORY_MESSAGES = 16
MAX_REPLY_LENGTH = 1900

if not DISCORD_TOKEN:
    raise RuntimeError("Set DISCORD_TOKEN in your .env file.")
if not AI_API_KEY:
    raise RuntimeError("Set AI_API_KEY in your .env file.")

intents = discord.Intents.default()
intents.message_content = True


class AIReplyBot(commands.Bot):
    async def setup_hook(self):
        self.http_session = aiohttp.ClientSession(
            timeout=aiohttp.ClientTimeout(total=60)
        )

    async def close(self):
        if hasattr(self, "http_session"):
            await self.http_session.close()
        await super().close()


bot = AIReplyBot(command_prefix="!", intents=intents)
channel_histories = defaultdict(list)
channel_locks = defaultdict(asyncio.Lock)
api_semaphore = asyncio.Semaphore(5)


async def generate_reply(history):
    headers = {
        "Authorization": f"Bearer {AI_API_KEY}",
        "Content-Type": "application/json",
    }
    payload = {
        "model": AI_MODEL,
        "messages": [{"role": "system", "content": SYSTEM_PROMPT}, *history],
        "max_tokens": 1000,
    }

    async with api_semaphore:
        async with bot.http_session.post(
            f"{AI_BASE_URL}/chat/completions", headers=headers, json=payload
        ) as response:
            if response.status >= 400:
                logger.error(
                    "AI API returned HTTP %s: %s",
                    response.status,
                    (await response.text())[:500],
                )
                raise RuntimeError(f"AI API returned HTTP {response.status}")
            data = await response.json()

    answer = data["choices"][0]["message"]["content"]
    if not isinstance(answer, str) or not answer.strip():
        raise RuntimeError("AI API returned an empty reply")
    return answer.strip()


def split_reply(text):
    parts = []
    while len(text) > MAX_REPLY_LENGTH:
        split_at = text.rfind("\n", 0, MAX_REPLY_LENGTH)
        if split_at < MAX_REPLY_LENGTH // 2:
            split_at = text.rfind(" ", 0, MAX_REPLY_LENGTH)
        if split_at < MAX_REPLY_LENGTH // 2:
            split_at = MAX_REPLY_LENGTH
        parts.append(text[:split_at].strip())
        text = text[split_at:].strip()
    if text:
        parts.append(text)
    return parts or ["I couldn't create a reply."]


@bot.event
async def on_ready():
    logger.info("Logged in as %s", bot.user)
    print("KODARI_READY", flush=True)


@bot.event
async def on_message(message):
    if message.author.bot or not message.content.strip():
        return

    channel_id = message.channel.id
    async with channel_locks[channel_id]:
        history = channel_histories[channel_id]
        updated_history = [
            *history,
            {"role": "user", "content": message.content.strip()},
        ]

        try:
            async with message.channel.typing():
                answer = await generate_reply(updated_history)
            updated_history.append({"role": "assistant", "content": answer})
            channel_histories[channel_id] = updated_history[-MAX_HISTORY_MESSAGES:]

            for index, part in enumerate(split_reply(answer)):
                if index == 0:
                    await message.reply(
                        part,
                        mention_author=False,
                        allowed_mentions=discord.AllowedMentions.none(),
                    )
                else:
                    await message.channel.send(
                        part, allowed_mentions=discord.AllowedMentions.none()
                    )
        except Exception:
            logger.exception("Failed to answer a message in channel %s", channel_id)
            try:
                await message.reply(
                    "I couldn't generate a reply right now. Please try again shortly.",
                    mention_author=False,
                    allowed_mentions=discord.AllowedMentions.none(),
                )
            except discord.HTTPException:
                logger.exception("Could not send the AI error reply")


bot.run(DISCORD_TOKEN)