NSFW LLM APINSFW LLM API Discord Bot Guide
NSFW LLM API Discord Bot Guide
A Discord bot on an OpenAI-compatible API needs about 70 lines of Python. This guide gives the code, a narrator prompt, limit handling and what each reply costs.

Key points
- Point the openai SDK at the API base URL and use the model ID uncensored.
- Answer only in age-restricted channels and set your own server rules for adults.
- Cap concurrency below 8, handle 429 with Retry-After, and skip streaming on Discord.
- A reply with 3,000 input and 300 output tokens costs $0.0006.
What you are building
An nsfw llm api discord bot is a small program that listens for messages in your server, sends the recent conversation to a chat completions endpoint, and posts the reply. With an OpenAI-compatible API the whole thing is about 70 lines of Python: a Discord client, the openai SDK pointed at https://api.nsfwllmapi.com/v1, and the model ID uncensored.
The recipe below is built for fiction, roleplay and companion-style chat among adults. The bot only answers when mentioned, only in channels that Discord marks as age-restricted, and keeps a short rolling history per channel. You need four things before you start:
- A Discord account with permission to add bots to your server.
- An API key for this service. The API key page lets new users claim a $0.50 trial credit with one click, which covers a full test run.
- Python 3.9 or newer.
- A machine that stays on, such as a small VPS or a spare computer, once you leave testing.
The model is text only. The bot cannot generate pictures, voices or music, and it cannot read images users upload. Plan the features around that from the start, and tell your members what the bot can and cannot do.
Set the rules before the code
A bot with an unfiltered model needs rules that live outside the model. The service is tuned to answer without content refusals for lawful adult use, with one hard limit: no sexual content involving minors. That limit applies to your server as well, and your community rules should say so in plain words.
Three practical measures keep the setup sensible:
- Use age-restricted channels. Discord has a setting for this on each channel, and the code in this guide refuses to reply anywhere else. Check Discord's current rules for what is allowed in your server, since they decide what you can host there, not this API.
- Gate access with a role. Give adults a role after your own verification and limit the bot channel to it.
- Keep moderators in the loop. Pick a channel where moderators can see bot output, and remove users who try to steer the bot toward banned content.
The code also keeps the narrator's prompt non-graphic. This is a style choice for a general adult server. You can change it in the system prompt, but keep your channel setting and your rules in step with whatever you choose.
Create the Discord application
In the Discord developer portal, create a new application, open its Bot tab and copy the bot token. This token is separate from your API key. Treat both as passwords and keep them in environment variables.
On the same Bot tab, switch on Message Content Intent. Without it the bot receives messages with an empty body and appears to ignore everyone, which is the most common first-run problem. Then open the OAuth2 URL generator, tick the bot scope, grant View Channels, Send Messages and Read Message History, and open the generated link to add the bot to your server.
Next, install the libraries and set the two secrets:
python -m venv .venv && source .venv/bin/activate
pip install discord.py openai
export DISCORD_TOKEN="your-discord-bot-token"
export LLM_API_KEY="your-api-key"Before writing the bot, test the API key alone. This one request should return a short reply and a JSON body with a usage block:
curl https://api.nsfwllmapi.com/v1/chat/completions \
-H "Authorization: Bearer $LLM_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"uncensored","messages":[{"role":"user","content":"Reply with the word ready."}],"max_tokens":10}'If it fails with 401, the key is wrong. If it works, you are ready for the full script. The quickstart lists the same request in other languages.
The bot, step by step
Save the following as bot.py. It uses the async client so that one slow reply does not freeze other channels.
import asyncio
import os
from collections import defaultdict, deque
import discord
from openai import AsyncOpenAI, RateLimitError, APIError
ai = AsyncOpenAI(
base_url="https://api.nsfwllmapi.com/v1",
api_key=os.environ["LLM_API_KEY"],
max_retries=0, # we handle 429 ourselves below
)
SYSTEM = (
"You are Ash, the narrator of a dark-fantasy roleplay server for adults. "
"Write in second person, present tense, in 80 to 150 words per reply. "
"Never speak for the player's character. Keep scenes non-graphic."
)
history = defaultdict(lambda: deque(maxlen=16)) # last 16 messages per channel
slots = asyncio.Semaphore(6) # stay under the limit of 8
intents = discord.Intents.default()
intents.message_content = True # also enable it in the developer portal
bot = discord.Client(intents=intents)
async def ask(channel_id, user_text):
history[channel_id].append({"role": "user", "content": user_text})
messages = [{"role": "system", "content": SYSTEM}, *history[channel_id]]
for _ in range(3):
try:
async with slots:
resp = await ai.chat.completions.create(
model="uncensored",
messages=messages,
temperature=0.9,
max_tokens=400,
)
text = resp.choices[0].message.content or ""
history[channel_id].append({"role": "assistant", "content": text})
return text
except RateLimitError as e:
await asyncio.sleep(int(e.response.headers.get("retry-after", "5")))
except APIError:
break
history[channel_id].pop() # drop the unanswered user message
return "The narrator is busy. Try again in a moment."
@bot.event
async def on_message(message):
if message.author.bot or bot.user not in message.mentions:
return
if not getattr(message.channel, "is_nsfw", lambda: False)():
return # only answer in age-restricted channels
text = message.content.replace(f"<@{bot.user.id}>", "").strip()
if not text:
return
async with message.channel.typing():
reply = await ask(message.channel.id, text)
for i in range(0, len(reply), 1900): # Discord caps a message at 2000 characters
await message.reply(reply[i:i + 1900], mention_author=False)
bot.run(os.environ["DISCORD_TOKEN"])A few choices in this code deserve an explanation.
History per channel
The deque(maxlen=16) keeps the last 16 messages for each channel and drops older ones. The model has a 100,000-token context window, far more than a Discord scene needs, so the limit is about cost and focus, not capacity. Sixteen short messages usually fit in 2,000 to 4,000 tokens with the system prompt. In a shared channel, several players write into one history, so prefix messages with the author name if you want the narrator to tell them apart.
No streaming
Streaming is supported through stream: true, but Discord throttles message edits, so updating a post on every chunk gets rate limited by Discord itself. A typing indicator followed by one complete reply works better and keeps the concurrency slot busy for a shorter time.
Handling limits
A full key allows 8 concurrent requests and 300 requests per minute. The semaphore caps the bot at 6 calls in flight. When the API still answers 429, the code waits for the Retry-After value (the service sends 5 seconds on temporary overload) and tries again, three times at most. Failed requests are not charged, so retries cost nothing extra. The error code distinguishes rate_limited, meaning too many requests per minute, from concurrency, meaning too many at once.
Write a system prompt that holds
The system prompt does most of the work of shaping a bot's voice. Keep it short, because it is sent with every request and you pay for it each time. The one in the code above is 53 words. A good prompt for a roleplay narrator answers four questions: who is speaking, in what person and tense, how long the replies should be, and what the bot must never do.
Here is the same setup as a raw request body, which is handy for testing prompt changes with curl or an API client before editing the script:
{
"model": "uncensored",
"messages": [
{"role": "system", "content": "You are Ash, the narrator of a dark-fantasy roleplay server for adults. Write in second person, present tense, 80 to 150 words per reply. Never speak for the player's character. Keep scenes non-graphic."},
{"role": "user", "content": "I push open the cellar door."}
],
"temperature": 0.9,
"max_tokens": 400
}Some patterns that work well in practice:
- State the length. "80 to 150 words" is more reliable than "be brief", and it fits Discord's reading rhythm.
- Name the boundary once. "Never speak for the player's character" prevents the most common roleplay complaint.
- Put the world in one paragraph. If the setting needs more, store it in a pinned message and paste a condensed version into the prompt.
- Test with hostile input. Try prompts that try to override the persona and tighten the wording when they succeed.
The sampling settings are passed through to the model, so you can tune them per channel: temperature around 0.8 to 1.0 for fiction, lower for a Q&A helper, top_p if you prefer nucleus sampling, and the frequency and presence penalties if replies start to repeat the same phrases. Setting seed makes reruns easier to compare while you tune the prompt.
What it costs to run
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, billed from prepaid credit. Take a typical bot call with 3,000 input tokens (system prompt plus 16 messages of history) and 300 output tokens:
- Input: 3,000 x 0.15 / 1,000,000 = $0.00045
- Output: 300 x 0.50 / 1,000,000 = $0.00015
- Per reply: $0.0006
Ten thousand replies cost $6.00, and the $0.50 trial covers about 833 replies (0.50 / 0.0006 = 833.3). A $20 top-up, the minimum, covers 33,333 replies at that size. Top-ups run from $20 to $500, larger ones carry a 5%, 10% or 15% bonus, and credit never expires, so a quiet server does not pay a monthly fee. This site accepts crypto only (USDT on TRC20 or USDC on Base). See the pricing page for the current bonus tiers.
Your real cost depends on how often people use the bot. Two measures keep it predictable: a per-user cooldown of a few seconds, and the max_tokens cap already in the code. A request counter per day will tell you what a "busy" server looks like before you commit to a larger top-up.
For a view of what is true and what is rumor about this kind of API, the page on NSFW chatbot API myths and facts is a short read.
Troubleshooting
| What you see | Why | What to do |
|---|---|---|
| Bot is online but never replies | Message Content Intent is off, or the channel is not age-restricted | Enable the intent in the portal and mark the channel |
| Error 401 from the API | Wrong or missing LLM_API_KEY | Re-copy the key; check that the shell exported it |
| Replies cut off mid-sentence | max_tokens=400 reached | Raise it, or ask for shorter replies in the prompt |
Frequent 429 with concurrency | Many channels active at once, or a trial key (limit 2) | Lower the semaphore; top up for a full key |
| Discord rejects the message | Reply is over 2,000 characters | The 1,900-character split in the code handles it |
| Bot forgets the story | History window is 16 messages | Raise maxlen or store a running summary in the prompt |
If you hit something not listed here, keep the X-Request-Id response header from the failing call and send it to support. Prompts are not used for training, and the privacy page explains what is kept.
More guides
Questions and answers
Can I run an NSFW LLM API Discord bot for free?
You can test it for free: new users claim a one-time $0.50 trial credit, valid for 7 days, which covers hundreds of replies. After that you pay per token from prepaid credit, starting with a $20 top-up.
Does the bot need streaming?
No. The API supports streaming, but Discord limits how fast a message can be edited, so one complete reply after a typing indicator is simpler and works better.
How much history can the bot remember?
The context window is 100,000 tokens, but most bots keep 10 to 20 recent messages to control cost. For longer stories, keep a short summary in the system prompt.
Is it allowed to run this bot on any server?
Discord's own rules and your channel settings decide that, so check their current policy. Keep the bot in age-restricted channels. The API itself never allows sexual content involving minors.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.