---
title: "Uncensored Discord bot in Python: a one-file guide"
canonical: https://unrestrictable.ai/guides/discord-bot
generated: 2026-11-16T02:57:39.847Z
source: https://unrestrictable.ai/guides/discord-bot
base_url: https://api.unrestrictable.ai/v1
---

# Run your own uncensored Discord bot from a single Python script

A self-hosted uncensored Discord bot: discord.py plus the OpenAI SDK on this API, four env vars, and it only speaks in the channels you choose.

Steps checked October 25, 2026 · prices as of November 16, 2026

One Python script is the whole bot. Mention it in a channel you have allowed and it sends that message to an uncensored model on this API through the OpenAI SDK, then posts the answer as a reply. Configuration is four environment variables. Everything below was checked against the discord.py and OpenAI SDK documentation on 25 October 2026.

Want to try the same models before writing any code? Open [/chat](https://unrestrictable.ai/chat): three free turns a day, no account. For background on how these builds differ from stock models, read [AI with no restrictions](https://unrestrictable.ai/blog/ai-with-no-restrictions) first.

## What you need

- Python 3.10 or later; the openai package requires it.
- A Discord account and a server where you may add apps.
- An API key from the [console](https://app.unrestrictable.ai/console).
- Two pip packages: discord.py 2.7.1 and openai 3.37.0, the PyPI versions on 25 October 2026.

Both libraries are built on asyncio. `AsyncOpenAI` awaits the model on the bot's own event loop, so a slow answer in one channel never blocks a message arriving in another. There is no framework and no build step, just one file.

A discord.js version with the OpenAI Node SDK works the same way. Python got the spot here because the script fits on one screen.

## Four environment variables, nothing else

- DISCORD_TOKEN: your-bot-token Copied from the Bot page in the Developer Portal
- UNR_API_KEY: sk-unr-live-… Generated in the console and displayed one time
- UNR_CHANNELS: 123456789012345678 Comma-separated channel ids the bot may speak in
- UNR_MODEL: glm-5.3-flash-uncensored Optional. Any id on the models page

The base URL, `https://api.unrestrictable.ai/v1`, is hard-coded in the script. Keys come from the [console](https://app.unrestrictable.ai/console), begin with `sk-unr-`, and draw on a prepaid balance you top up from $10. No ID check, no subscription.

## Register the app in Discord's Developer Portal

Button and page names follow Discord's [getting started guide](https://docs.discord.com/developers/quick-start/getting-started) as it read on 25 October 2026.

1. Open the Developer Portal, give the new application a name and click **Create**.
2. Go to the **Bot** page. In the **Token** section click **Reset Token** and store the value in `DISCORD_TOKEN`. It is displayed a single time.
3. On the **Installation** page pick the Discord Provided Link, and under **Default Install Settings** add the `bot` scope to Guild Install.
4. A permissions picker appears. Tick Send Messages and Read Message History. The bot answers by replying to the message that mentioned it, and Discord's message docs make Read Message History a requirement for that.
5. Visit the install link, pick **Add to server**, and confirm the bot has access to every channel it should respond in.
6. Switch on **Developer Mode** (User Settings, Advanced). Right-click a channel, pick **Copy Channel ID**, and add each id to `UNR_CHANNELS`.

You do not need any privileged intent. The script only handles messages that mention the bot, and Discord's [gateway docs](https://docs.discord.com/developers/events/gateway) carve "content in which the app is mentioned" out of the Message Content intent.

## bot.py, the whole program

Name the file `bot.py`. The discord.py quickstart warns against calling it `discord.py`, which would shadow the library itself.

```python
# bot.py: replies to @mentions in your allowed channels using an uncensored model.
import os
import re

import discord
from openai import APIStatusError, AsyncOpenAI

MODEL = os.environ.get("UNR_MODEL", "glm-5.3-flash-uncensored")
SYSTEM = (
    "You are a blunt, helpful member of this Discord server. "
    "Answer in plain text, under 1,500 characters."
)

CHANNELS = {int(c) for c in os.environ.get("UNR_CHANNELS", "").split(",") if c.strip()}

llm = AsyncOpenAI(base_url="https://api.unrestrictable.ai/v1", api_key=os.environ["UNR_API_KEY"])
client = discord.Client(intents=discord.Intents.default())

def listed(channel) -> bool:
    # Threads inherit their parent channel. DMs have no listed id, so they are ignored.
    return channel.id in CHANNELS or getattr(channel, "parent_id", None) in CHANNELS

@client.event
async def on_ready():
    print(f"Logged in as {client.user}")

@client.event
async def on_message(message: discord.Message):
    if message.author.bot or client.user not in message.mentions:
        return
    if not listed(message.channel):
        await message.reply("I only answer in the channels I am set up for.")
        return
    prompt = re.sub(rf"<@!?{client.user.id}>", "", message.content).strip()
    if not prompt:
        return
    try:
        async with message.channel.typing():
            reply = await llm.chat.completions.create(
                model=MODEL,
                messages=[
                    {"role": "system", "content": SYSTEM},
                    {"role": "user", "content": prompt},
                ],
                max_tokens=500,
            )
    except APIStatusError as err:
        await message.reply(f"The model API answered {err.status_code}.")
        return
    text = reply.choices[0].message.content or "(empty reply)"
    await message.reply(text[:2000])

client.run(os.environ["DISCORD_TOKEN"])
```

On an @mention it makes a single request to the API and posts the answer as a reply in that channel. Replies are trimmed to 2,000 characters, the message content cap in Discord's docs. No history travels with the request, so each call stays small.

## Keep it to the channels you list

Only ids in `UNR_CHANNELS` get answers. Threads inherit their parent channel through the `parent_id` attribute discord.py gives them. Mentions elsewhere, DMs included, get a short notice and no API call, so they cost nothing.

Whatever the bot writes is subject to Discord's [Community Guidelines](https://discord.com/guidelines) (in force since 29 September 2025; read 25 October 2026) and to Discord's [Developer Policy](https://support-dev.discord.com/hc/en-us/articles/8563934450327-Discord-Developer-Policy) for apps, worth reading before the bot joins servers that are not yours. Our [acceptable use policy](https://unrestrictable.ai/acceptable-use) covers the API side.

## Start it

```bash
python3 -m pip install discord.py openai
export DISCORD_TOKEN="your-bot-token"
export UNR_API_KEY="sk-unr-live-…"
export UNR_CHANNELS="123456789012345678"   # channel ids, comma-separated
export UNR_MODEL="glm-5.3-flash-uncensored"   # optional
python3 bot.py
```

When the terminal prints "Logged in as", Discord took the token. Go to an allowed channel and mention the bot with a prompt, say a villain's speech for the next session of your campaign. Discord shows a typing indicator until the answer lands. The bot stays up as long as the process does, on a laptop or a small VPS.

## Three builds that suit a channel bot

Prices and windows below were read from the catalog when this page was built. The verdict column comes from [the daily real-model check](https://unrestrictable.ai/proof), which sends every model the same prompt once a day.

| Model | Build | Input $/M | Output $/M | Context | Wire formats |
| --- | --- | --- | --- | --- | --- |
| [GLM-5.3 Flash Uncensored](https://unrestrictable.ai/models/glm-5.3-flash-uncensored) glm-5.3-flash-uncensored | Uncensored | $0.1053 | $0.3685 | — | openai |
| [GLM-5.3 Uncensored](https://unrestrictable.ai/models/glm-5.3-uncensored) glm-5.3-uncensored | Uncensored | $0.282 | $0.846 | — | openai |

Prices per million tokens, read from the live catalog on 2026-11-16.

| Model id | Today's verdict | Window |
| --- | --- | --- |
| [`glm-5.3-flash-uncensored`](https://unrestrictable.ai/models/glm-5.3-flash-uncensored) | Steady since Oct 12 | not published |
| [`glm-5.3-uncensored`](https://unrestrictable.ai/models/glm-5.3-uncensored) | Steady since Oct 12 | not published |

Windows: live catalog, 2026-11-16. Verdicts: /proof at render time.

Pick the flash build for a channel with a lot of traffic. For a character, set `UNR_MODEL` to `roleplay-uncensored` and put the persona in `SYSTEM`. The [Character AI alternatives](https://unrestrictable.ai/blog/character-ai-alternatives) post lists more builds made for characters.

## Monthly cost for a busy server

Assume 300 replies every day for 30 days. A request carries roughly 200 tokens (system prompt plus the user's message) and the answer is roughly 300 tokens.

| Model | 9,000 replies in a month |
| --- | --- |
| [GLM-5.3 Flash Uncensored](https://unrestrictable.ai/models/glm-5.3-flash-uncensored) | $1.18 |
| [GLM-5.3 Uncensored](https://unrestrictable.ai/models/glm-5.3-uncensored) | $2.79 |

Worked out at render from the catalog prices on 2026-11-16: replies × 200 input tokens at the input rate, plus replies × 300 output tokens at the output rate.

The biggest lever is memory. Send the previous ten messages as context and every request grows by their size. The `max_tokens=500` line keeps the output side bounded. Per-token rates for every model are on the [pricing page](https://unrestrictable.ai/pricing).

## Test the key with one curl

The request below returns the model ids your key can use. It is free and comes back at once.

```bash
curl https://api.unrestrictable.ai/v1/models \
  -H "Authorization: Bearer sk-unr-live-…"
```

A 200 and a list of ids: the key is fine, and `UNR_MODEL` has to be one of those ids. A 401 tells you what is wrong with the key:

```
HTTP 401
{"error":{"message":"No API key was sent.","type":"authentication_error","param":null,"code":"invalid_api_key"}}
```

```
HTTP 401
{"error":{"message":"The API key is not valid.","type":"authentication_error","param":null,"code":"invalid_api_key"}}
```

Both responses are verbatim from the API on 25 October 2026.

## When something breaks

### The bot posts "The model API answered 401"

`UNR_API_KEY` is missing, mistyped or revoked. Run the curl above with that exact key.

### "The model API answered 404"

`UNR_MODEL` does not match any catalog id:

```
HTTP 404
{"error":{"message":"No such model: glm-5.3-flash-uncensord.","type":"not_found_error","param":null,"code":"model_not_found"}}
```

### "The model API answered 402"

Your prepaid balance has run out. Top up in the console and the next mention goes through.

```
HTTP 402
{"error":{"message":"The prepaid balance does not cover this request. Top up at … to continue.","type":"insufficient_quota","param":null,"code":"insufficient_balance"}}
```

### "I only answer in the channels I am set up for"

That channel's id is missing from `UNR_CHANNELS`. Copy it again with Developer Mode on. A server id or a message id pasted by mistake will never match.

### PrivilegedIntentsRequired at startup

The script requested an intent that is switched off in the Developer Portal, and Discord dropped the connection with close code 4014. As written, the script requests none. If you add `message_content`, turn it on under the Bot page too.

### Forbidden on reply

discord.py raises `Forbidden` when a permission is missing. Confirm Send Messages and Read Message History on that channel. The [docs page](https://unrestrictable.ai/docs) carries the base URL, key and model id for other clients.

## Questions

### Can I just add an existing uncensored Discord bot?

Directories like top.gg and discord.bots.gg carry hosted bots. The script here is the self-hosted route: you choose the model and each reply is billed to your own key.

### How do I stop the bot answering everywhere?

List the allowed channel ids in UNR_CHANNELS, separated by commas. Threads count under their parent channel. Everywhere else the bot posts a short notice and makes no API call.

### Is the Message Content intent required?

No. Discord delivers messages that mention the bot without that intent, and those are the only ones the script reads. Requesting the intent in code while it is off in the portal raises PrivilegedIntentsRequired.

### Does this work in discord.js too?

Yes. Point the OpenAI Node SDK at baseURL https://api.unrestrictable.ai/v1 with your key and port the same logic. A Node snippet is on the docs page. See the docs page.

### What model works best for a Discord bot?

Any id that speaks the OpenAI wire format. Flash builds keep a high-traffic channel affordable; a roleplay build fits a character. See the uncensored model list.

### What does running one cost?

Tokens only. The table above prices a month of replies at live catalog rates. No subscription: you prepay a balance and spend it per token. See per-token prices.

Every model above is on the [uncensored model list](https://unrestrictable.ai/models) with its live price per million tokens. [Per-token pricing](https://unrestrictable.ai/pricing) sets the whole catalog side by side, and the [family directory](https://unrestrictable.ai/uncensored) groups the builds by base model.

[Get a key](https://app.unrestrictable.ai/console) Prepaid from $10, no subscription.

## New models and price changes, once a month.

New uncensored builds with their prices, price moves, and what the daily model check found.
