Skip to content
AI Agent How-To

Home ›Connect agents to apps

How to Connect an AI Agent to Discord (discord.py)

Intermediate ~7 min read Last tested November 2026

Updated 2026-11-10

This guide connects a Python AI agent to Discord with discord.py. The bot listens for @mentions, loads recent channel history for context, and replies with an LLM call you can later upgrade to the tool loop from Build your first AI agent in Python. Run it on your laptop for testing or in Docker on a small VPS for a 24/7 community bot. Schedule digests with Build an AI agent that runs on a schedule. Last tested 2026-11-10.

Prerequisites

  • A Discord account and permission to create applications in the Discord Developer Portal
  • Python 3.10+ and an LLM API key (OPENAI_API_KEY or any OpenAI-compatible provider)

Docs used:

Steps

1. Create the Discord application

  1. Open discord.com/developers/applications and click New Application.
  2. Go to Bot → Add Bot and copy the token (DISCORD_TOKEN). Never commit it.
  3. Under Privileged Gateway Intents, turn on Message Content Intent. Without it, the bot cannot read message text in most servers after Discord’s 2022 policy change.
  4. Open OAuth2 → URL Generator. Select the bot scope and permissions Send Messages, Read Message History, and Add Reactions. Copy the generated URL and use it to invite the bot to a test server.

2. Install dependencies

python -m venv .venv && source .venv/bin/activate
pip install "discord.py>=2.4" openai
export DISCORD_TOKEN="..." OPENAI_API_KEY="sk-..."

3. Write a mention-triggered bot

# discord_agent.py
import os, re
import discord
from openai import OpenAI

intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
llm = OpenAI()
MODEL = os.environ.get("MODEL", "gpt-4.1-mini")

def strip_mention(content: str, bot_id: int) -> str:
    return re.sub(rf"<@!?{bot_id}>", "", content).strip()

@client.event
async def on_ready():
    print(f"Logged in as {client.user} (id={client.user.id})")

@client.event
async def on_message(message: discord.Message):
    if message.author.bot:
        return
    if client.user not in message.mentions:
        return

    user_text = strip_mention(message.content, client.user.id)
    history = []
    async for msg in message.channel.history(limit=15, before=message):
        role = "assistant" if msg.author.id == client.user.id else "user"
        text = strip_mention(msg.content, client.user.id) if role == "user" else msg.content
        if text:
            history.append({"role": role, "content": text[:4000]})
    history.reverse()
    messages = [
        {"role": "system", "content": "You are a helpful Discord assistant. Be concise."},
        *history,
        {"role": "user", "content": user_text or "Hello"},
    ]
    reply = llm.chat.completions.create(model=MODEL, messages=messages).choices[0].message.content
    await message.reply(reply[:2000])  # Discord message limit

client.run(os.environ["DISCORD_TOKEN"])

This follows the event pattern from the discord.py quickstart, with message_content intent enabled.

4. Run and test

python discord_agent.py

In your test server, @mention the bot in a channel it can read. It should reply in the same channel and use the last several messages as context.

5. Add the tool loop

Replace the single chat.completions.create call with the loop and TOOLS / FUNCS pattern from Build your first AI agent in Python. Keep max_steps low so a mention cannot run unbounded tool calls in a public channel.

6. Deploy for always-on use

Package the bot with How to deploy an AI agent with Docker or run it on a small VPS from DigitalOcean. Discord Gateway bots need outbound internet; they do not require a public HTTP URL unless you switch to slash commands with an interactions endpoint.

Common errors

Bot comes online but never responds to text. Message Content Intent is off, or the bot lacks Read Message History / Send Messages in that channel. Re-enable the intent in the Developer Portal, re-invite with updated permissions, and check channel overrides.

discord.errors.PrivilegedIntentsRequired. You enabled message_content in code but not in the Developer Portal. Turn it on under Bot → Privileged Gateway Intents and restart the bot.

401 Unauthorized on client.run. The bot token was reset or pasted incorrectly. Copy a fresh token from Bot → Reset Token.

Replies truncate mid-sentence. Discord caps messages at 2000 characters. Split long replies into multiple messages or summarize.

Rate limits (429 Too Many Requests). Back off with asyncio.sleep when the API returns rate limit headers, and avoid broadcasting the same LLM call to many channels at once.

FAQ

How do I connect an AI agent to Discord?

Create a bot application, enable Message Content Intent, invite the bot with send/history permissions, and run discord.py with an on_message handler that checks @mentions before calling your LLM or agent loop.

Do I need a public URL for a Discord agent?

No for this Gateway bot. Your process opens an outbound WebSocket to Discord. HTTP interaction endpoints are only required for certain slash-command or webhook setups.

Can I use Discord MCP instead of discord.py?

Discord does not ship a first-party MCP server in this guide’s sense. Hosted MCP in Cursor targets products like Slack or Gmail; for a custom community bot, discord.py remains the supported API path.

How is this different from the Slack guide?

Slack Bolt often uses Socket Mode with app tokens. Discord uses a single bot token and Gateway intents. Both patterns @mention the bot and keep thread or channel history.