From empty droplet to a chat bot that answers around the clock

APIFreeKeyOpenAI · Updated 2026-11-24 · 8 min read

A small glowing server next to headphones and a game controller
A tiny VPS is enough when the model runs elsewhere.

One-click server images make it look easy to get an AI assistant running on a cloud droplet. Then comes the gap people keep describing: the server is up, but the bot does not actually answer. Tokens are missing, the process dies when you close the terminal, the bot cannot read messages, or the model connection fails silently.

This guide closes that gap with a minimal, understandable setup. You will create a Discord application, write a short Python bot that calls an OpenAI-compatible API, run it as a system service that restarts on failure, and add the small features that make it usable in a real server: per-channel context, message splitting and polite handling of rate limits.

The bot starts on the keyless free-ai endpoint, so there is no model key to manage. You can switch to a paid provider later by changing two environment variables. This site is not affiliated with OpenAI or Discord.

Frequently asked questions

What is a bot token?

It is the secret credential that lets your code log in as the bot in Discord. Anyone who has it can control the bot. Store it in an environment file readable only by the service user, and regenerate it in the developer portal if it ever leaks.

Why does my bot connect but not see message text?

Reading message content requires the message content intent, which must be enabled both in the developer portal and in your code. Without it the bot receives events but the text field is empty.

How does a VPS differ from running the bot on my laptop?

A VPS stays online when your laptop sleeps and has a stable network. It also needs basic administration: updates, a firewall and a service manager so the bot restarts after crashes and reboots.

Which is better for a small bot, a keyless endpoint or a paid key?

For a hobby or small community bot, a keyless endpoint removes cost and secret handling. For a large or business-critical bot, a paid API gives stronger models, higher limits and support. Starting keyless and switching later is a common path.

Does the bot remember conversations?

The API is stateless, so the bot must keep recent messages itself and send them with each request. Keeping a short rolling window per channel is enough for natural follow-ups without inflating requests.

What limits apply to the free endpoint?

Per server IP, about one request per second with bursts of three, two concurrent requests, and a daily ceiling of 10,000 requests or 10 million tokens, reset at midnight UTC. A busy community can hit these, so add a small queue and a cooldown.

Can the bot use OAuth instead of a token?

Bots log in with a bot token. OAuth flows are for users authorizing applications. For the model side, subscription sign-in for agents has its own limits, which we discuss in subscription sign-in vs API keys.

Will the bot generate anything users ask for?

free-ai refuses less often than commercial assistants, but it never produces sexual content involving minors or operational instructions for mass-casualty weapons. You should also add your own rules suited to your community, such as channel restrictions and moderation.

Step by step

  1. Create the bot — Make a Discord application, add a bot, copy its token and enable the message content intent.
  2. Prepare the VPS — Create an unprivileged user, a Python virtual environment, and install discord.py and openai.
  3. Store configuration — Write the bot token, base URL, placeholder key and model name to an environment file with mode 600.
  4. Add the bot code — Save the Python bot that answers mentions, keeps short per-channel history and limits concurrent calls.
  5. Install the service — Create a systemd unit with automatic restart, enable it and check the logs.
  6. Test and tune — Mention the bot in a channel, then add cooldowns and adjust history length to fit your community.

What you need before starting

The requirements are modest. A small Linux VPS with one virtual CPU and a gigabyte of memory is plenty, because the model runs elsewhere and the bot only relays messages. You need Python 3.10 or newer, a Discord account with permission to add bots to a server, and about half an hour.

Decide early which model route the bot will use. The examples default to the keyless endpoint at https://api.apifreekeyopenai.com/v1 with model free-ai. If you plan to use a paid provider, have its base URL, key and model name ready.

Pick a region near your users

Latency to Discord matters less than you might think, but a server near most of your members makes responses feel snappier.

Create a non-root user

Run the bot as its own unprivileged user. If the bot code ever misbehaves, it cannot touch the rest of the system.

Creating the Discord application

In the Discord developer portal, create a new application, add a bot to it and copy the bot token. Enable the message content intent on the bot settings page, since without it your bot cannot read what people write.

Generate an invite link with the bot scope and the permissions to read and send messages in the channels you want. Open the link and add the bot to your server. It will appear offline until your code runs.

Least privilege

Do not grant administrator permission to a chat bot. If its token leaks, an admin bot can wreck a server in seconds; a read-and-reply bot cannot.

Use a test server first

Create a small private Discord server just for development and invite the bot there before adding it to a real community. You can experiment with prompts, break things and restart the bot as often as you like without spamming anyone. Once it behaves well, generate a second invite link for the production server with the same minimal permissions.

  • Create the application and bot.
  • Copy the token once and store it safely.
  • Enable the message content intent.
  • Invite the bot with read and send message permissions only.
A brass key inside a small open safe
Treat the bot token like a key to the whole bot.

Preparing the server

Log in to the VPS, update packages, create a user for the bot and set up a Python virtual environment. Install two libraries: discord.py for the bot and openai for the model client.

Put configuration in an environment file in the bot user's home directory with restrictive permissions. Never paste the token into the code itself, where it could end up in a repository.

Firewall

A Discord bot makes only outgoing connections. You can block all incoming traffic except SSH, which removes a whole category of risk.

sudo adduser --disabled-password --gecos "" aibot
sudo -iu aibot bash -c '
  python3 -m venv ~/venv
  ~/venv/bin/pip install --upgrade discord.py openai
  mkdir -p ~/bot
  cat > ~/bot/.env <<EOT
DISCORD_TOKEN=paste-your-bot-token-here
LLM_BASE_URL=https://api.apifreekeyopenai.com/v1
LLM_API_KEY=not-needed
LLM_MODEL=free-ai
EOT
  chmod 600 ~/bot/.env
'

The bot code

The bot below answers when it is mentioned, keeps the last few exchanges per channel, splits long replies to fit Discord's message limit and serializes model calls so it never exceeds two in flight. It runs the blocking API call in a thread so the bot stays responsive.

The model client is the standard openai SDK pointed at whatever base URL is in the environment, which is what makes switching providers trivial.

Why a semaphore

It caps concurrent model calls at two, matching the free endpoint's per-IP limit. Extra requests wait their turn instead of failing with 429.

Why a bounded history

Eight messages per channel give enough context for follow-ups while keeping each request small. Unbounded history would grow until it hit the 32,000-token context window.

import asyncio, os
from collections import defaultdict, deque
import discord
from openai import OpenAI

llm = OpenAI(base_url=os.environ["LLM_BASE_URL"], api_key=os.environ.get("LLM_API_KEY", "not-needed"))
MODEL = os.environ.get("LLM_MODEL", "free-ai")
SYSTEM = {"role": "system", "content": "You are a friendly, concise helper in a Discord server."}

history = defaultdict(lambda: deque(maxlen=8))
slots = asyncio.Semaphore(2)

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

def ask(messages):
    r = llm.chat.completions.create(model=MODEL, messages=messages, max_tokens=600)
    return r.choices[0].message.content or "(no answer)"

@bot.event
async def on_message(msg: discord.Message):
    if msg.author.bot or bot.user not in msg.mentions:
        return
    text = msg.clean_content.replace(f"@{bot.user.name}", "").strip()
    h = history[msg.channel.id]
    h.append({"role": "user", "content": f"{msg.author.display_name}: {text}"})
    async with msg.channel.typing(), slots:
        try:
            reply = await asyncio.to_thread(ask, [SYSTEM, *h])
        except Exception as e:
            reply = f"Sorry, the model is unavailable right now ({type(e).__name__})."
    h.append({"role": "assistant", "content": reply})
    for i in range(0, len(reply), 1900):
        await msg.reply(reply[i:i + 1900], mention_author=False)

bot.run(os.environ["DISCORD_TOKEN"])
A wooden robot figure sorting envelopes into pigeonholes
The bot keeps a short history per channel and answers in turn.

Running it as a service

A bot started from an SSH session dies when the session ends. A systemd unit keeps it running, restarts it after crashes and starts it at boot. It also loads the environment file so the code can read the token.

After creating the unit, enable and start it, then watch the logs for the first minute. A successful login and a reply to a test mention mean you are done with the basics.

Useful commands

Use sudo systemctl enable --now aibot to start it and journalctl -u aibot -f to follow the logs. Restart after code changes with sudo systemctl restart aibot.

# /etc/systemd/system/aibot.service
[Unit]
Description=AI Discord bot
After=network-online.target
Wants=network-online.target

[Service]
User=aibot
WorkingDirectory=/home/aibot/bot
EnvironmentFile=/home/aibot/bot/.env
ExecStart=/home/aibot/venv/bin/python /home/aibot/bot/bot.py
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

Living with rate limits

Busy channels produce bursts of mentions. The semaphore prevents overload, and the openai SDK retries a 429 or 503 a couple of times on its own. On top of that, a short per-user cooldown keeps one enthusiastic member from consuming the whole budget.

Track daily usage. On the free endpoint the server's IP gets 10,000 requests or 10 million tokens per day, resetting at 00:00 UTC. If your community regularly approaches that, it is time to consider a paid route for the bot.

Per-user cooldown

Store the last request time per user and ignore mentions within, say, ten seconds. Reply once with a friendly note so people know why.

Graceful degradation

When the model is unavailable, say so briefly rather than staying silent. Users forgive a busy bot; they get confused by one that just ignores them.

Answering only where invited

Restrict the bot to specific channels by checking the channel ID before replying. A bot that answers every mention everywhere quickly becomes noise, and it uses the shared daily allowance on conversations nobody intended for it. A short allow list in the environment file is easy to update without touching the code, and it keeps the bot welcome in the community.

Toy figures waiting at a turnstile one at a time
Two calls in flight, the rest wait their turn.

Connecting the bot to other tools

Many teams want their bot to read from project trackers, wikis or ticket systems. When you connect such services, prefer long-lived scoped API tokens over OAuth flows whose tokens expire within an hour, which several integrations are known for. A bot that must be re-authorized every morning is not really always-on.

Store each integration token the same way as the bot token, with minimal scopes. If the bot only needs to read issues, do not give it permission to edit them.

Tool calls through the model

For simple lookups, let your code fetch data and include it in the prompt rather than giving the model open-ended tool access. It is easier to control and cheaper.

Security and maintenance

Keep the system updated, the bot user unprivileged and the environment file readable only by that user. Rotate the bot token if you ever paste it anywhere public, including into an AI chat; see keeping secrets out of prompts for why that matters.

Every request the bot sends to the free endpoint leaves a technical log there with time, IP, User-Agent, country, endpoint, status, latency, sizes and tokens, but no stored conversation. Tell your community that messages to the bot are processed by an external model so nobody is surprised.

Unattended loops

If you later add autonomous features, such as scheduled summaries, put step and token caps on them. Our article on stopping runaway agent loops lists the guardrails.

  • Enable unattended security updates.
  • Back up the bot code and environment file.
  • Review the logs weekly for errors and abuse.
  • Keep the bot's Discord permissions minimal.
A toolbox and padlock on a server cabinet
Updates, minimal permissions and rotated tokens keep the bot healthy.
Try the free API

Send a prompt to the keyless free-ai endpoint from the home page and see a reply in seconds, no sign-up needed.

Read also