EN ▾

unhinged.topHosted uncensored API for developers

Build an Unrestricted AI Discord Bot

Isometric illustration of chat bubbles flowing from a bot node into Discord-style channel panels

An unrestricted AI Discord bot is a normal bot with one change: the model behind it does not refuse lawful adult requests. This article shows the code, the memory logic and the monthly bill.

Updated

Key points

  1. The bot is about 60 lines of Python using discord.py and the standard OpenAI SDK, with the base URL pointed at this API.
  2. Keep a short rolling history per channel so replies stay coherent without paying for a huge prompt every time.
  3. Cap concurrent requests under 8 and let the SDK retry 429 responses.
  4. A busy bot at 1,000 replies a day costs about $11.25 a month at the listed token prices.

What makes a Discord bot unrestricted

A bot with no content filter is not a special kind of bot. Discord only sees a program that reads messages and posts replies. The behavior you care about lives entirely in the language model that writes those replies. If the model is tuned to refuse a large share of fiction, dark humor or blunt opinions, your bot will refuse them too, no matter how clever your code is.

This API serves one open-weight model, run by an independent provider and tuned to answer without content refusals for lawful adult use. It speaks the OpenAI chat completions format, so any bot library that can call OpenAI can call it after a base URL change. The model ID is uncensored, and the base URL is https://api.unhinged.top/v1.

One limit is fixed and not negotiable: no sexual content involving minors. That applies to the model and to the servers you run. The rest of this article assumes an adult community, such as a fiction or roleplay server, a comedy server with a rough tone, or a private friend group that wants a bot with no filter on its personality.

What you need before writing code

  1. A Discord application. Create one in the Discord developer portal, add a bot user, copy the token and keep it out of your repository.
  2. The message content intent. Bots that read ordinary messages must enable the Message Content privileged intent in the portal. Without it, message.content arrives empty and the bot looks broken.
  3. An API key. Sign up with Google or with email and password, then open the API key page. New users can claim $0.50 of trial credit there with one click, valid for 7 days, no payment needed.
  4. Python 3.10 or newer. Install discord.py and openai with pip.

Store both secrets as environment variables. The code below reads DISCORD_TOKEN and UNHINGED_API_KEY. Invite the bot to your server with the bot scope and permission to read and send messages in the channels where it should talk.

The bot, start to finish

This version answers when someone mentions it. Mention-only triggering keeps costs predictable, because the bot never reacts to chatter it was not asked about.

import os
import asyncio
from collections import defaultdict, deque

import discord
from openai import AsyncOpenAI, RateLimitError

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

SYSTEM = (
    "You are Mara, a sharp-tongued character in a fiction server for adults. "
    "Stay in character, be direct, and keep replies under 1500 characters."
)

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

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


def chunks(text, size=1900):
    for i in range(0, len(text), size):
        yield text[i:i + size]


@bot.event
async def on_message(message):
    if message.author.bot or bot.user not in message.mentions:
        return
    text = message.clean_content.replace("@" + bot.user.name, "").strip()
    if not text:
        return

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

    async with slots, message.channel.typing():
        try:
            resp = await ai.chat.completions.create(
                model="uncensored",
                messages=[{"role": "system", "content": SYSTEM}, *log],
                temperature=0.9,
                max_tokens=500,
            )
        except RateLimitError:
            await message.reply("Too many people talking to me at once. Try again in a few seconds.")
            return

    reply = resp.choices[0].message.content or "..."
    log.append({"role": "assistant", "content": reply})
    for part in chunks(reply):
        await message.channel.send(part)


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

Three details matter here. The Semaphore(6) keeps the bot under the concurrency cap of 8 for a full key, with a little room left for your own tests. The chunks helper exists because Discord rejects messages longer than 2,000 characters, and a model with a 100,000-token window can easily write more than that. And max_retries=3 tells the SDK to retry on its own when the API answers 429.

Memory without a bloated prompt

The model has no memory between requests. Whatever the bot should remember must be sent again each time. The code above keeps the last 12 messages per channel in a deque, which is the simplest approach that works. Each user line carries the speaker name, so the model can tell apart four people arguing in the same channel.

You pay for input tokens on every request, so history length is the main cost lever. A few practical choices:

  • Short window for chat servers. Twelve messages is enough for banter. Eight is often fine.
  • Longer window for story channels. Raise maxlen to 40 or more. The 100,000-token context window is shared by prompt and completion, so there is plenty of space, but each extra message is paid for again on every reply.
  • Pinned facts. If a campaign needs a fixed world description, put it in the system prompt rather than hoping it stays inside the rolling window.
  • Reset command. Add a slash command or a keyword that clears history[channel_id], so a derailed scene can be restarted cheaply.

Memory held in a Python dict disappears when the process restarts. For most hobby bots that is acceptable. If you want persistence, write the deque to SQLite or a JSON file after each reply and load it at startup.

Rate limits and what to do about them

A full key allows 8 concurrent requests and 300 requests per minute. The trial key allows 2 concurrent requests and 60 per minute. A small server will not come near these numbers. A server with several hundred active members can.

The API signals trouble with HTTP 429. The error code is rate_limited when you exceed requests per minute and concurrency when too many requests run at once. On temporary overload you also get 429, with a Retry-After: 5 header. The OpenAI SDK reads that behavior as a retryable error and waits before trying again, which is why the example sets max_retries.

If you later switch to streaming so that messages appear gradually, remember that a streamed request holds its concurrency slot until the stream ends. A slow stream is a long-lived slot. Keep the semaphore in place and keep it below 8.

Check the response headers when debugging. X-Balance-USD shows what is left on the account, and X-Request-Id is what you quote if you contact support about one specific call.

What it costs to run

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit. There is no subscription, failed or refused requests are not charged, and credit never expires. The pricing page has the top-up tiers.

Take a busy server where the bot sends 1,000 replies a day. Each request carries the system prompt plus 12 history lines, say 1,500 input tokens, and the model writes about 300 tokens back.

ItemTokens per dayPriceCost per day
Input1,000 x 1,500 = 1.5M$0.15 per 1M$0.225
Output1,000 x 300 = 0.3M$0.50 per 1M$0.150
Total$0.375

Over 30 days that is $11.25. One reply costs $0.000375, so the $0.50 trial credit covers roughly 1,333 replies, enough to test a bot with a real group of friends. If you trim history to a window that averages 600 input tokens, input drops to 0.6M tokens a day, which is $0.09, and the daily total falls to $0.24, or $7.20 a month.

Top-ups are by crypto (USDT on TRC20, USDC on Base), any whole amount from $20 to $500. Larger top-ups add a bonus of 5% from $50, 10% from $100 and 15% from $200. A $20 balance covers the busy-server example for a bit over seven weeks.

Improving the bot after the first version

Once the basic version answers reliably, a few upgrades are worth the time. None of them change the API calls much, because the request format stays the same.

Slash commands

Mentions are fine for small servers, but slash commands are easier to discover. A /ask command for one-off questions and a /reset command that clears the channel history cover most needs. In discord.py, the app commands extension handles registration for you.

Per-channel personas

Keep a dictionary that maps channel IDs to system prompts. The bot can then play a cynical bartender in one channel and a game master in another, using the same code and the same uncensored model. Because the persona sits in the system message, switching costs nothing extra.

Structured output for game logic

If the bot runs a text game, ask the model for JSON with fields such as narration, hp_change and items, and set response_format to {"type": "json_object"}. Your code can then update a scoreboard from the parsed fields and post only the narration. Tool calling works too, with the standard tools and tool_choice parameters, if you prefer the model to request actions such as dice rolls.

Timeouts and failure messages

Network calls fail sometimes. Wrap the request in asyncio.wait_for with a generous timeout, and send a short apology if it expires, so users do not wait on a silent channel. Refused or failed requests are not charged, so an honest retry costs you nothing.

Running a server with an unfiltered bot

Removing model refusals moves moderation to you. A few habits keep a server healthy:

  • Restrict the bot to specific channels and mark mature channels as age-restricted in Discord. Check your own server rules and Discord's current terms for what is allowed where.
  • Give the system prompt explicit boundaries for your community. The model follows a clear persona and clear limits well.
  • Never allow content involving minors. It is a hard limit of this service, and it should be a hard rule on your server too.
  • Log who triggered each reply so you can answer a complaint with facts.

Prompts sent through the API are not used for training. Read the privacy page for details, and tell your members that their messages in bot channels are sent to an external model provider. For model behavior and trade-offs, the page on the Unhinged AI model covers cost and speed in more depth, and the docs list every supported parameter.

01

Questions and answers

Do I need a paid account to test the bot?

No. After sign-up you can claim $0.50 of trial credit with one click on the API key page. It is valid for 7 days, needs no payment, and works with a limit of 2 concurrent requests.

Can I use discord.js instead of discord.py?

Yes. The API is OpenAI-compatible, so the official OpenAI package for Node works the same way. Set the base URL to https://api.unhinged.top/v1 and the model to uncensored.

Why does the bot reply with nothing in a server channel?

Most often the Message Content intent is off, either in the developer portal or in your code. The bot then receives events with empty text. Enable it in both places.

Can the bot call tools or return JSON?

Yes. Tool calling and JSON mode (response_format with json_object) are supported, which is useful for slash commands that need structured output.

Your key is one form away

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

Get API keyRead the docs