EN ▾

Heretic LLM Discord Bot: Build One with the API

You can build a heretic llm discord bot with a short Python script: discord.py receives messages, and an OpenAI-compatible endpoint writes the replies. This guide covers the setup, a system prompt, memory per channel, rate limits and what each message costs.

Updated

Glowing chat bubbles linked by cables to a central hub, illustrating a Discord bot connected to a language model API

Key points

  • The bot is discord.py plus the standard OpenAI Python SDK pointed at the API base URL with model uncensored.
  • Enable the Message Content intent in the Discord developer portal so the bot can read channel messages.
  • Keep a short history per channel and cap parallel calls at 8, the full-key concurrency limit.
  • A chat turn with 3,000 tokens of history and a 300 token reply costs $0.0006.

What you are building

A heretic llm discord bot, as built here, is a small program that logs in to Discord as a bot user, listens for messages that mention it, sends the channel history to a language model and posts the answer back. Nothing about it is exotic. The only unusual part is the model: it is an open-weight text model that answers without content refusals for lawful adult use, so a fiction or roleplay server does not get its scenes interrupted by canned disclaimers.

This is a build-it-yourself guide. You host the bot process, you hold the Discord bot token, and you pay per token for the model calls. The model is text only, so the bot cannot create or read images, and its context window is 100,000 tokens (prompt plus completion), which is far more than a Discord channel needs.

The steps in order: create the Discord application, get an API key, run the code below, then tune the system prompt and limits.

Set up Discord and the API key

  1. Open the Discord developer portal, create a new application and add a bot to it. Copy the bot token and treat it like a password.
  2. On the bot page, switch on the Message Content Intent. Without it, Discord withholds message text except in direct messages and in messages that mention the bot. Turn it on so features that read normal channel messages work later.
  3. Generate an invite link under OAuth2 with the bot scope and the permissions to read messages, send messages and read message history. Invite the bot to a test server you control.
  4. Sign up on the API key page with Google or with email and password. New users can claim $0.50 of trial credit with one click, valid for 7 days, no card needed.
  5. Install the libraries and export both secrets as environment variables.
pip install discord.py openai
export DISCORD_TOKEN="your-discord-bot-token"
export API_KEY="your-api-key"

Before you write any bot code, confirm the key works with a single request:

curl https://api.hereticllm.top/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "uncensored", "messages": [{"role": "user", "content": "Say hello in one sentence."}]}'

If you get JSON back with a reply, the endpoint, key and model ID are correct. The quickstart in the docs shows the same call in other languages.

The bot code

This version answers when someone mentions the bot or writes in a direct message. It keeps a rolling history for each channel, limits parallel model calls and splits long answers to fit Discord's 2,000 character message limit.

import os
import asyncio
from collections import defaultdict, deque

import discord
from openai import AsyncOpenAI, APIError, RateLimitError

ai = AsyncOpenAI(
    base_url="https://api.hereticllm.top/v1",
    api_key=os.environ["API_KEY"],
    max_retries=3,
)

SYSTEM_PROMPT = (
    "You are Mara, the narrator of a collaborative dark-fantasy story on a "
    "Discord server for adults. Stay in character, keep replies under 250 words, "
    "write in second person for the player who spoke last, and end each reply "
    "with a hook the players can act on. Never write sexual content involving "
    "minors. If a player asks you to step out of the story, answer plainly."
)

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

history = defaultdict(lambda: deque(maxlen=30))
slots = asyncio.Semaphore(6)


def split_message(text, limit=1900):
    parts = []
    while len(text) > limit:
        cut = text.rfind("\n", 0, limit)
        if cut < limit // 2:
            cut = text.rfind(" ", 0, limit)
        if cut <= 0:
            cut = limit
        parts.append(text[:cut])
        text = text[cut:].lstrip()
    if text:
        parts.append(text)
    return parts


@bot.event
async def on_message(message: discord.Message):
    if message.author.bot:
        return
    is_dm = isinstance(message.channel, discord.DMChannel)
    if not (is_dm or bot.user in message.mentions):
        return

    text = message.clean_content.replace(f"@{bot.user.display_name}", "").strip()
    if not text:
        return

    log = history[message.channel.id]
    log.append({"role": "user", "content": f"{message.author.display_name}: {text}"})
    messages = [{"role": "system", "content": SYSTEM_PROMPT}] + list(log)

    async with message.channel.typing():
        try:
            async with slots:
                resp = await ai.chat.completions.create(
                    model="uncensored",
                    messages=messages,
                    temperature=0.8,
                    top_p=0.95,
                    max_tokens=600,
                )
        except RateLimitError:
            await message.reply("The narrator is busy. Try again in a few seconds.")
            return
        except APIError:
            await message.reply("Something went wrong on my side. Please try again.")
            return

    reply = resp.choices[0].message.content or ""
    log.append({"role": "assistant", "content": reply})
    for i, chunk in enumerate(split_message(reply)):
        if i == 0:
            await message.reply(chunk)
        else:
            await message.channel.send(chunk)


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

Run it with python bot.py, then mention the bot in your test server. The first reply may take a few seconds while the model generates.

Writing the system prompt

The system prompt does most of the work in a Discord bot. A model without content refusals follows it closely, so be specific about the role, the length and the format. The example above fixes four things: who the bot is, how long replies run, whose perspective to write from and how each reply ends. Short replies matter on Discord; a 600 word wall of text scrolls everyone's conversation away.

Settings worth adjusting

  • temperature: 0.7 to 0.9 suits storytelling and banter. Drop to 0.3 for a helper bot that answers rules questions.
  • top_p: leave near 0.95 unless replies feel repetitive.
  • max_tokens: optional, but a cap of 400 to 600 keeps replies Discord-sized and controls cost.
  • frequency_penalty and presence_penalty: passed through to the model; a small positive value, such as 0.3, reduces loops in long roleplay sessions.
  • seed: useful when you want to reproduce a reply while debugging a prompt.
  • stop: set a stop sequence if the model tends to write the other players' lines for them.

Put your server's rules in the prompt too. If your community is for adults and bans certain topics, say so; the model will follow the rule you give it. The one rule that does not depend on your prompt is the hard limit on sexual content involving minors, which this API never produces.

Memory, context and what it costs

The bot above remembers the last 30 messages per channel in plain memory. That is a deliberate choice: a deque is simple, it forgets on restart, and it keeps the prompt small. One thing to know is that trimming from the left can leave an assistant message at the start of the history, which the model tolerates well. If you want continuity across restarts, store the history in SQLite or Redis, and keep the stored text private, since your database is not covered by the API's promise that prompts are not used for training.

Your context budget is large, 100,000 tokens, but you pay for every input token on every call, so history length is the main cost lever. Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens.

  • Short history. 3,000 tokens in, 300 tokens out. Input: 3,000 x $0.15 / 1M = $0.00045. Output: 300 x $0.50 / 1M = $0.00015. Total $0.0006 per message, so 1,000 messages cost $0.60.
  • Long history. 20,000 tokens in, 300 out. Input: 20,000 x $0.15 / 1M = $0.003. Output is the same $0.00015. Total $0.00315 per message, so 1,000 messages cost $3.15.

The smallest top-up is $20, which covers about 33,000 messages of the first kind (20 / 0.0006). Top-ups run in any whole amount from $20 to $500, with +5% from $50, +10% from $100 and +15% from $200, by crypto. Credit never expires, which suits a hobby server whose traffic comes in bursts. Details are on the pricing page.

Rate limits and long replies

A full key allows 8 concurrent requests and 300 per minute; a trial key allows 2 and 60. The semaphore in the code is set to 6 so a few slots stay free for your own tests. On a trial key, set it to 2 and expect the "narrator is busy" message when three players write at once. A rate limit surfaces as HTTP 429 with the code rate_limited or concurrency, and a temporary overload as 429 with Retry-After: 5. The OpenAI SDK retries 429 responses with a short delay, and max_retries=3 in the client gives it three tries before the bot gives up.

Failed or refused requests are not charged, so a busy moment costs you nothing but a delay. For a busy public server, add a per-user cooldown of a few seconds so one enthusiastic player cannot fill all the slots.

Streaming or not

The API supports streaming over SSE, but on Discord it rarely pays off. To show text as it arrives you would edit the same message again and again, and Discord rate limits message edits. Waiting for the full reply with the typing indicator on is simpler and behaves better. If you do stream, remember that a stream holds its concurrency slot until it ends.

Running it responsibly

Treat the server the way you would treat any adult-only space. Use Discord's age-restricted channel setting where it applies, state your rules in the channel topic and keep moderator tools close. Discord's own terms and community guidelines apply to the bot and the server regardless of which model you use, and the use of this API is for lawful adult use only.

A few operational habits save trouble later:

  • Keep the bot token and API key in environment variables, never in the repository.
  • Log X-Request-Id from failed calls so you can reference it when you write to support.
  • Watch the X-Balance-USD header, or check the balance now and then, so the bot does not go quiet in the middle of a session.
  • Add a command that clears a channel's history, for the moment a scene goes off the rails and needs a restart.

For tool calling, JSON mode and the rest of the request options, the documentation is the reference. A bot that rolls dice or looks up a character sheet is a natural use for tool calling, since the API supports tools and tool_choice with results returned as role: "tool" messages.

Questions and answers

Do I need to host the bot myself?

Yes. The bot is a process you run on your own machine or server. The API only handles the model calls, which the bot sends over HTTPS.

Which model ID do I use in a Discord bot?

Use uncensored as the model value with the base URL https://api.hereticllm.top/v1 and your key as a Bearer token. Any OpenAI SDK works unchanged otherwise.

Can the bot generate images or voice?

No. The model is text only, so there is no image, audio or video generation and no embeddings. The bot works with text messages.

Why does my bot see empty message text?

Usually the Message Content Intent is off. Enable it on the bot page in the Discord developer portal and also set intents.message_content = True in the code.

Is there a free way to test it?

New users can claim $0.50 of trial credit on the API key page. It lasts 7 days, needs no card and runs at 2 concurrent requests and 60 per minute.

Your key is one form away

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

Get API key