EN ▾
Get API key
Get API key

Discord Bots for Roleplay: Build One with an LLM API

A roleplay bot on Discord is a small program that listens to a channel and answers in character. This walkthrough builds one in Python with an OpenAI-compatible API, and covers memory, limits and cost.

Updated:

Isometric chat panel with colored circles linked to a central lantern node, picturing a Discord roleplay bot

Key points

  • The bot needs discord.py, the openai package, a Discord bot token and an API key.
  • Keep a short message history per channel and trim it, instead of resending everything.
  • Use non-streaming replies on Discord, because message edits are rate-limited.
  • At roughly 2,800 prompt tokens and 200 output tokens, a reply costs about $0.00052.

How the pieces fit

Public discord bots for roleplay usually do the same job: someone mentions the bot, the bot reads recent messages, asks a language model for the next line of the story, and posts it. Discord handles the chat. Your code handles memory. The API supplies the writing.

The model here is one open-weight model, tuned to answer without content refusals for lawful adult use, behind an OpenAI-compatible interface. You use the normal openai Python package and change two values: the base URL https://api.roleplayapi.com/v1 and the key. The model ID is uncensored. For full request details, see the quickstart docs.

Create the Discord application

  1. Open the Discord Developer Portal, create a new application, and add a Bot to it.
  2. Copy the bot token and store it in an environment variable. Never paste it into a repository.
  3. On the Bot page, switch on the Message Content Intent. Without it the bot receives empty message text.
  4. Under OAuth2, generate an invite URL with the bot scope and permissions to view channels, send messages and read message history.
  5. Invite the bot to a test server first.

Then get an API key from the key page. New users can claim $0.50 of trial credit with one click after sign-up, which is enough to test a server of friends.

The bot code

Install the packages:

pip install discord.py openai

Then save this as bot.py. It answers when mentioned, keeps a separate history for each channel, and splits long answers to fit Discord's 2,000-character limit.

import asyncio
import os
import re

import discord
from openai import AsyncOpenAI

ai = AsyncOpenAI(
    base_url="https://api.roleplayapi.com/v1",
    api_key=os.environ["ROLEPLAY_API_KEY"],
)

SYSTEM = (
    "You are Maren, a dry, tired tavern owner in a rain-soaked port city. "
    "Write only Maren and the world, never the players' actions. "
    "Several players may speak; their names appear before each message. "
    "Keep replies to 1 to 3 short paragraphs. All participants are adults."
)

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

history = {}                    # channel id -> list of messages
gate = asyncio.Semaphore(6)     # stay under 8 concurrent requests
KEEP = 30


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

    text = re.sub(r"<@\D?\d+>", "", message.content).strip()
    if not text:
        return

    log = history.setdefault(message.channel.id, [])
    log.append({"role": "user", "content": message.author.display_name + ": " + text})
    del log[:-KEEP]

    async with message.channel.typing():
        try:
            async with gate:
                result = await ai.chat.completions.create(
                    model="uncensored",
                    messages=[{"role": "system", "content": SYSTEM}] + log,
                    temperature=0.9,
                    max_tokens=500,
                )
        except Exception as exc:
            await message.channel.send("The bot hit an error. Try again in a moment.")
            print("API error:", exc)
            return

    reply = result.choices[0].message.content or "..."
    log.append({"role": "assistant", "content": reply})
    for start in range(0, len(reply), 1900):
        await message.channel.send(reply[start:start + 1900])


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

Run it with both variables set: ROLEPLAY_API_KEY and DISCORD_TOKEN. Mention the bot in a channel and it answers.

Design choices that matter on Discord

Do not stream into Discord

The API supports streaming over SSE, and it is great in a web app. On Discord, showing live text means editing one message over and over, and edits are rate-limited. A single complete message after a typing indicator is more reliable and looks fine.

Tag who said what

Discord roleplay is usually multiplayer. Prefixing each user line with the display name lets the model tell players apart, and the system prompt says so. Without that, it merges everyone into one speaker.

Several characters from one bot

Discord webhooks can post with a custom name and avatar. If your scene has a narrator, a rogue and an innkeeper, ask the model to label lines by speaker, split them in code, and post each through a webhook. Players see separate characters, and you still pay for one request.

One history per channel, in memory

The dictionary above resets when the process restarts. For a persistent campaign, save each channel's list to a file or a small database, and add a command to clear it when a scene ends.

Running it for real

A script on your laptop is fine for testing. For a bot that stays online, a few additions make a large difference.

  • Hosting. Any small server or container that can keep one Python process alive will do. The bot is light, since the heavy work happens on the API side.
  • Restarts. Run it under a process manager so it comes back after a crash, and write channel histories to disk so a restart does not erase a campaign.
  • Cooldowns. Allow one pending request per user. It stops one enthusiastic player from filling the queue, and it keeps costs predictable.
  • A reset command. Let a moderator type a short command that clears the channel's history when a scene ends. Long stale history makes replies slower to read and more expensive.
  • Logging. Log the request ID from the X-Request-Id response header with each error. If something goes wrong, you can quote it when you ask for help.

For a server with a fixed cast, build separate bots or separate personas per channel by storing a different system prompt for each channel ID. A tavern channel and a dungeon channel can then run side by side from one process.

Limits you should plan for

A full key allows 8 concurrent requests and 300 requests per minute. The trial key allows 2 and 60. The semaphore in the code caps the bot at 6 in flight, so a busy channel waits instead of failing. The maximum request body is 8 MB, which a text chat will not approach. Each response includes X-RateLimit-Limit-Requests, X-RateLimit-Limit-Concurrency and X-Balance-USD, so you can log them.

Context is 100,000 tokens, prompt plus completion. Your 30-message cap keeps a bot far below that, which is good for cost and for focus.

What running it costs

Price is $0.15 per 1M input tokens and $0.50 per 1M output tokens. With a 400-token system prompt plus 30 messages averaging 80 tokens, a request carries about 2,800 tokens, and the reply is about 200 tokens.

  • Input: 2,800 × $0.15 / 1,000,000 = $0.00042
  • Output: 200 × $0.50 / 1,000,000 = $0.0001
  • Total: $0.00052 per reply

Ten thousand replies cost $5.20, and a $20 top-up covers about 38,000. Failed or refused requests are not billed. Top up by crypto (USDT on TRC20, USDC on Base), any whole amount from $20 to $500, with +5% from $50, +10% from $100 and +15% from $200. See the pricing page for details.

Server rules and content

Discord has its own rules, and adult fiction belongs in channels set up for it. Follow the platform's current policies, and keep mature content in age-restricted channels. On our side, the use is lawful adult fiction only, and sexual content involving minors is never allowed. Your prompts are not used for training.

Questions and answers

Do I need the Message Content Intent?

Yes, if the bot reads normal messages. Turn it on in the Bot page of the Developer Portal, and pass intents.message_content = True in code.

Can one bot serve several servers?

Yes. Keep history per channel, as in the example, and watch the 8 concurrent request limit if traffic grows.

Which model name should the bot send?

Send uncensored as the model ID, with the base URL https://api.roleplayapi.com/v1.

What happens if the API call fails?

The bot catches the error and posts a short notice. Failed requests are not charged, so retrying costs nothing extra.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.