EN ▾

How to Make a Discord Generator Bot with an LLM API

A Discord generator bot is a small program that takes a prompt from a channel, sends it to a language model and posts the answer back. This article shows how to make a discord generator bot in about 80 lines of Python, using an OpenAI-compatible endpoint.

Updated

Isometric chat bubbles flowing from a chat window into a terminal, for a Discord bot calling an API

What a generator bot actually does

Strip away the branding and every generator bot has the same loop. A user types a prompt. The bot forwards it to a model with a system message that fixes the job, such as writing short scripts, captions, character names or story hooks. The model returns text. The bot posts that text back into the channel. Everything else is housekeeping: history, limits, error handling and permissions.

This API only produces text. It does not draw images and it does not render video, so a generator bot built on it writes things like video scripts, shot lists, prompts for a separate image tool, dialogue and lore. If you want a bot that hands back pictures, the text from this bot can feed an image service you run yourself, but the image step is outside this API. The model is an open-weight model tuned to answer without content refusals for lawful adult use, which matters when your server is built around fiction and roleplay that other hosted models tend to decline.

The API follows the OpenAI chat format, so the official openai Python package works after you change two values: the base URL and the key. The model ID is uncensored. If you have never called the API before, the API docs list every parameter that is passed through.

What you need before writing code

  1. A Discord application and bot token. Create an application in the Discord developer portal, add a bot user, and copy the token. Keep it in an environment variable, never in the source file.
  2. The Message Content intent. If you want the bot to react when someone mentions it, switch on the Message Content intent for the bot in the portal. Slash commands do not need it.
  3. An API key. Sign up on the API key page. New users can claim $0.50 of trial credit with one click, valid for 7 days, with no payment needed. A trial key allows 2 concurrent requests and 60 requests per minute, which is enough to test a bot in a private server.
  4. Python 3.9 or newer with discord.py and openai installed through pip.

Invite the bot to a test server first, using the OAuth2 URL generator in the portal with the bot and applications.commands scopes. Give it permission to read and send messages in the channels where it should work, and nothing more.

Before you write any Discord code, check that the key works with a plain request. If this prints a JSON answer, the API side is done:

curl https://api.unrestrictedvideogenerator.top/v1/chat/completions \
  -H "Authorization: Bearer $LLM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "messages": [{"role": "user", "content": "Give me five names for a space-pirate podcast."}],
    "max_tokens": 120
  }'

A 401 means the key is wrong or missing the Bearer prefix. A 429 on a first call is unusual and points at the trial limits, so wait a few seconds and run it once more.

The complete bot

The file below is a working bot with two ways to trigger it: the /generate slash command and a plain mention. Save it as bot.py, export DISCORD_TOKEN and LLM_API_KEY, and run it with python bot.py.

import asyncio
import os

import discord
from discord import app_commands
from openai import AsyncOpenAI, RateLimitError

ai = AsyncOpenAI(
    base_url="https://api.unrestrictedvideogenerator.top/v1",
    api_key=os.environ["LLM_API_KEY"],
    max_retries=4,
)

SYSTEM = (
    "You are a writing helper inside a Discord server. "
    "You produce scripts, captions, names and story ideas on request. "
    "Keep answers under 600 words and use plain text."
)
slots = asyncio.Semaphore(6)   # stay under the 8 concurrent requests of a full key
history = {}                   # channel id -> recent messages


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


async def ask(channel_id, prompt):
    msgs = history.setdefault(channel_id, [])
    msgs.append({"role": "user", "content": prompt})
    del msgs[:-12]             # keep the last 12 messages only
    async with slots:
        try:
            resp = await ai.chat.completions.create(
                model="uncensored",
                messages=[{"role": "system", "content": SYSTEM}] + msgs,
                temperature=0.8,
                max_tokens=900,
            )
        except RateLimitError:
            return "The API is busy right now. Try again in a minute."
    text = resp.choices[0].message.content or ""
    msgs.append({"role": "assistant", "content": text})
    return text


class Bot(discord.Client):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True
        super().__init__(intents=intents)
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self):
        await self.tree.sync()


bot = Bot()


@bot.tree.command(name="generate", description="Generate text from a prompt")
@app_commands.describe(prompt="What should I write?")
async def generate(interaction: discord.Interaction, prompt: str):
    await interaction.response.defer(thinking=True)
    text = await ask(interaction.channel_id, prompt)
    for chunk in split_text(text):
        await interaction.followup.send(chunk)


@bot.event
async def on_message(message):
    if message.author.bot or bot.user not in message.mentions:
        return
    prompt = message.content.replace(bot.user.mention, "").strip()
    if not prompt:
        return
    async with message.channel.typing():
        text = await ask(message.channel.id, prompt)
    for chunk in split_text(text):
        await message.reply(chunk)


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

A few choices in that file are worth explaining, because each one answers a problem you will meet within the first hour.

One system prompt defines the generator

The SYSTEM string is the only place where the bot gets its personality and its job. Change it and the same code becomes a name generator, a scene writer or a character voice. Keep it short and specific, and state the output shape you want. A line such as "Reply with exactly five numbered options" works better than a paragraph of tone advice.

History is per channel and capped

The model has no memory between requests. The bot sends the last twelve messages each time, which is enough for a follow-up like "make it shorter". A cap matters for cost, since every old message is billed again as input on each new call. The context window is 100,000 tokens, so you will not hit the ceiling with twelve messages, but a long-running channel without a cap would grow the bill for no benefit.

The mention path and the command path share one function

Both handlers call ask(). That keeps limits, history and error text in one place. When you add a third entry point later, such as a context-menu command, it takes three lines.

Why the slash command defers its reply

Discord gives a bot three seconds to respond to a slash command. A model answer of several hundred tokens can take longer than that, so the handler calls interaction.response.defer(thinking=True) first. Discord then shows a "thinking" state and accepts follow-up messages for the next fifteen minutes. Skip the defer and users see "The application did not respond" even though your code is still working.

For the mention path the equivalent is the typing indicator, which the example starts with message.channel.typing(). It does nothing for correctness, but people stop sending the same prompt three times when they can see the bot is busy.

If you want text to appear as it is written, the API supports streaming with stream: true and returns usage at the end. On Discord this is less useful than in a web chat, because editing one message many times runs into Discord's own rate limits on edits. A practical compromise is to collect the stream and edit the message once every second or two, or to skip streaming and send the finished text.

Message length and rate limits

Discord rejects any message longer than 2,000 characters. The split_text() helper cuts at the last line break before 1,900 characters, falls back to a hard cut when there is no good break, and returns a list your handler sends in order. The 100-character margin leaves room if you later add a prefix such as a username. Setting max_tokens to 900 also keeps answers from running into many chunks. The parameter is optional on this API, since a completion can use whatever is left of the 100,000-token window, but a cap protects your credit from a runaway answer.

On the API side, a full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. Past the limit you get HTTP 429, with the error code rate_limited for too many requests per minute and concurrency for too many at once. During temporary overload the API also answers 429 with a Retry-After: 5 header. The response headers X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency tell you the limits your key has.

The example handles this in two layers. A semaphore of 6 keeps the bot below the concurrency cap of a full key, so a burst of ten users in a channel queues up instead of failing. The OpenAI client is created with max_retries=4, and the Python SDK waits and retries on 429, honouring the Retry-After value. If all retries fail, the bot answers with a plain message rather than a stack trace. On a trial key, change the semaphore to 1 or 2.

Remember that a streamed request holds its concurrency slot until the stream ends. If you add streaming later, the semaphore must stay held for the whole stream, not just the first token.

What a generator bot costs to run

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, billed from prepaid credit. Failed or refused requests are not charged. Here is a typical turn for the bot above: a 300-token system prompt and history, a 200-token user prompt, and a 400-token reply. That is 500 input tokens and 400 output tokens, or 1,500 input tokens once the history has filled up.

CaseInput costOutput costPer reply
500 in, 400 out500 x $0.15 / 1M = $0.000075400 x $0.50 / 1M = $0.0002$0.000275
1,500 in, 400 out1,500 x $0.15 / 1M = $0.000225400 x $0.50 / 1M = $0.0002$0.000425

At the higher figure, 1,000 replies cost $0.425 and 10,000 replies cost $4.25. A community server that sees 300 generations a day would spend about $0.13 a day. The smallest top-up is $20, so the first deposit would cover many months of that traffic. Credit never expires, and there is no subscription. See the pricing page for the bonus tiers on larger top-ups: +5% from $50, +10% from $100 and +15% from $200. Payment is in crypto, USDT on TRC20 or USDC on Base.

Rules, moderation and safe defaults

A model that does not refuse is a tool you configure responsibly. Run it in a server whose members are adults, and put adult-oriented generation in channels that Discord lets you mark as age-restricted. Discord's own terms and developer policy apply to your bot regardless of what the API allows, so read them before you invite the bot to a public server. The API has one hard limit: it will not produce sexual content involving minors, and your bot should drop any prompt that tries.

Some habits keep a public bot manageable:

  • Add a per-user cooldown, for example one request every ten seconds, so one person cannot use up the concurrency slots.
  • Limit the bot to specific channels with a check on message.channel.id.
  • Log the X-Request-Id header of failed calls so you can reference it if you contact support.
  • Watch X-Balance-USD in the response headers and warn yourself in a private channel when credit drops below a threshold.
  • Do not paste the API key or the Discord token into a chat. If one leaks, rotate it.

Prompts are not used for training, but your Discord server still stores its own history. Tell your members what the bot sends to an outside API.

Questions and answers

Can the bot generate images or video in Discord?

No. The API returns text only. The bot can write scripts, captions and prompts, and you can pass those to an image or video tool that you run separately.

Do I need a paid key to test the bot?

No. A trial key with $0.50 of credit, claimed with one click after sign-up, is enough to test. It is valid for 7 days, allows 2 concurrent requests and 60 requests per minute, and needs no payment.

Which library should I use, discord.py or discord.js?

Either works. The API is a plain HTTPS endpoint in the OpenAI format, so the openai package for Node plays the same role as the Python one. Set the base URL, the key and the model ID uncensored.

Why does the bot ignore mentions?

The Message Content intent is usually off. Enable it in the developer portal and set intents.message_content to True in the code.

How do I stop the bot from repeating itself?

Lower the history length, raise temperature a little, and pass presence_penalty or frequency_penalty. The API passes these parameters through.

Your key is one form away

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