A Discord bot built on discord.js keeps one WebSocket connection open to Discord's gateway and reacts to the events that arrive on it, so hosting it means keeping a single process running day and night, restarting it on new versions without ever running two copies at once. On Modelence the bot is a service in modelence.config.json with no health check port and a rollout that stops the old container before the new one logs in. It runs as a container on AWS in the region you pick out of 17, and a managed PostgreSQL, MongoDB or Redis database can sit next to it.
This guide builds a small bot with three slash commands: /ping, /roll, and /note, which saves notes for each server in PostgreSQL. It covers creating the application in the Discord Developer Portal, registering the commands, running the bot on your machine and deploying it. A bot with more commands, buttons or scheduled messages deploys the same way, and the config section is the part to copy if your bot already works locally.
Discord bot on Modelence at a glance
- Library
- discord.js 14, the most downloaded Discord library on npm, which needs Node.js 18 or newer
- Start command
- node bot.js after npm ci, on the official node-22-slim image, with a migration run just before it
- Health check
- None, since the bot opens no port and talks to Discord over an outgoing gateway connection
- Rollout
- recreate, so the old container logs out before the new one logs in and each command gets one reply
- Commands
- Slash commands are registered by a separate script you run when they change, not on every start
- Intents
- Only the Guilds intent, which needs no approval from Discord because slash commands carry their own input
- Data
- Managed PostgreSQL, MongoDB or Redis in the same AWS region, reached through a connection string
Before you start
- Node.js 18 or newer and npm
- A Discord account and a server where you can add apps, to test the bot in
- A Modelence account, which you can create for free
Create the bot application
In the Discord Developer Portal, create a new application. On its Bot page, click Reset Token and copy the token, which is the bot's password and goes into the DISCORD_TOKEN variable later. Copy the Application ID from General Information as well. To add the bot to your test server, open OAuth2, tick the bot and applications.commands scopes in the URL generator, give it the Send Messages permission and open the generated link.
Create two applications this way, one for production and one for testing. The test bot is the one you run from your laptop, so working on a new command never answers people in the servers where the real bot lives.
Then create the project and install discord.js:
mkdir my-bot && cd my-bot
npm init -y
npm pkg set type=module
npm install discord.js
Each command lives in commands.js as a pair of a definition, built with SlashCommandBuilder, and an execute function. The registration script and the bot both import this list, so a command's name and options are written once. /ping reports the gateway latency only to the person who asked, through MessageFlags.Ephemeral, and /roll takes an optional number of sides that Discord itself keeps between 2 and 1000.
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
export const commands = [
{
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Check that the bot is online'),
async execute(interaction) {
await interaction.reply({
content: `Pong! Gateway latency is ${interaction.client.ws.ping} ms.`,
flags: MessageFlags.Ephemeral,
});
},
},
{
data: new SlashCommandBuilder()
.setName('roll')
.setDescription('Roll a die')
.addIntegerOption((option) =>
option.setName('sides').setDescription('Number of sides, 6 by default').setMinValue(2).setMaxValue(1000),
),
async execute(interaction) {
const sides = interaction.options.getInteger('sides') ?? 6;
const result = Math.floor(Math.random() * sides) + 1;
await interaction.reply(`${interaction.user} rolled ${result} on a d${sides}.`);
},
},
];Write the bot process
bot.js connects to the gateway, waits for interactions and hands each slash command to its execute function. A few choices in it matter once the bot is hosted:
- The client asks only for the
Guildsintent. Slash commands bring their options with them, so the bot doesn't need Message Content, the privileged intent Discord reviews for bots in more than 100 servers. - A command that throws gets an ephemeral "Something went wrong." reply instead of leaving the user with "The application did not respond", and the error goes to the logs.
- On
SIGTERM, which arrives when a deploy replaces the container,client.destroy()closes the gateway connection before the process exits. client.loginreads the token fromDISCORD_TOKEN, so it never sits in the code.
import { Client, Events, GatewayIntentBits, MessageFlags } from 'discord.js';
import { commands } from './commands.js';
const commandsByName = new Map(commands.map((command) => [command.data.name, command]));
// Slash commands need only the Guilds intent, which isn't privileged.
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.once(Events.ClientReady, (ready) => {
console.log(`Logged in as ${ready.user.tag} in ${ready.guilds.cache.size} servers`);
});
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const command = commandsByName.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(`/${interaction.commandName} failed`, error);
const reply = { content: 'Something went wrong.', flags: MessageFlags.Ephemeral };
const send = interaction.replied || interaction.deferred ? interaction.followUp(reply) : interaction.reply(reply);
await send.catch(console.error);
}
});
// Close the gateway connection when the container stops, before the new version logs in.
process.on('SIGTERM', async () => {
await client.destroy();
process.exit(0);
});
await client.login(process.env.DISCORD_TOKEN);Register the slash commands once
Discord keeps the list of an application's slash commands on its side, so commands are registered with a REST call rather than each time the bot connects. The discord.js guide recommends a separate script for this, and Discord limits an application to 200 new commands a day in each server. Add deploy-commands.js, which sends the whole list in one request, and a register script for it in package.json:
"scripts": {
"start": "node bot.js",
"dev": "node --watch bot.js",
"register": "node deploy-commands.js"
}
Run it whenever you add a command or change one's options, not when you only change what a command does. With DISCORD_GUILD_ID set to your test server's ID (turn on Developer Mode in Discord's settings, then right-click the server), the commands appear there right away. Without it they're registered globally, for every server the bot is in. Register the test application's commands against your test server and the production application's commands globally:
DISCORD_TOKEN=<test bot token> DISCORD_CLIENT_ID=<test application id> DISCORD_GUILD_ID=<server id> npm run register
DISCORD_TOKEN=<bot token> DISCORD_CLIENT_ID=<application id> npm run register
import { REST, Routes } from 'discord.js';
import { commands } from './commands.js';
const { DISCORD_TOKEN, DISCORD_CLIENT_ID, DISCORD_GUILD_ID } = process.env;
const body = commands.map((command) => command.data.toJSON());
// With DISCORD_GUILD_ID, the commands go to one test server and show up at once.
const route = DISCORD_GUILD_ID
? Routes.applicationGuildCommands(DISCORD_CLIENT_ID, DISCORD_GUILD_ID)
: Routes.applicationCommands(DISCORD_CLIENT_ID);
const rest = new REST().setToken(DISCORD_TOKEN);
const registered = await rest.put(route, { body });
console.log(`Registered ${registered.length} commands`);Run the bot locally
Start the test bot with its token. npm run dev restarts it whenever a file changes:
DISCORD_TOKEN=<test bot token> npm run dev
The terminal prints Logged in as <bot name> in 1 servers, and typing / in your test server lists the bot's commands. A token that's missing or wrong stops the bot at once with TokenInvalid: An invalid token was provided., which is the first thing to check when a bot won't start, here or after a deploy.
Add a database
- MongoDB
MONGODB_URI - Postgres
DATABASE_URL - Redis
REDIS_URL
Anything the bot should remember after a restart, such as settings for each server, user balances or saved notes, needs a database, because a container's memory and disk start empty on every deploy. Modelence creates managed PostgreSQL, MongoDB and Redis in the bot's region and passes the connection string to it as a variable, and production databases are backed up.
This bot uses PostgreSQL through pg (npm install pg). db.js opens one connection pool for the process, and migrate.js creates the table if it doesn't exist yet:
// db.js
import pg from 'pg';
// One pool for the whole process.
export const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
// migrate.js
import { pool } from './db.js';
await pool.query(`
CREATE TABLE IF NOT EXISTS notes (
id bigserial PRIMARY KEY,
guild_id text NOT NULL,
author_id text NOT NULL,
text text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
)
`);
await pool.end();
console.log('Database is up to date');
The /note command below saves a note for the current server or lists the latest five. Import it in commands.js with import { note } from './note-command.js';, add note to the commands array and run npm run register again. Prisma or Drizzle work the same way with their own migrate commands. For cooldowns and rate limits, Redis is the usual choice, and MongoDB suits bots that store loosely shaped documents per server.
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { pool } from './db.js';
export const note = {
data: new SlashCommandBuilder()
.setName('note')
.setDescription('Save a note for this server, or list the latest five')
.addStringOption((option) =>
option.setName('text').setDescription('Leave empty to list notes').setMaxLength(500),
),
async execute(interaction) {
const text = interaction.options.getString('text');
if (text) {
await pool.query('INSERT INTO notes (guild_id, author_id, text) VALUES ($1, $2, $3)', [
interaction.guildId,
interaction.user.id,
text,
]);
return interaction.reply({ content: 'Saved.', flags: MessageFlags.Ephemeral });
}
const { rows } = await pool.query(
'SELECT text FROM notes WHERE guild_id = $1 ORDER BY id DESC LIMIT 5',
[interaction.guildId],
);
await interaction.reply(rows.length ? rows.map((row) => `- ${row.text}`).join('\n') : 'No notes yet.');
},
};Describe the bot in modelence.config.json
The file below runs the bot as one service and creates its PostgreSQL database. The settings that make it a bot rather than a web server are on the service:
"healthCheck": { "type": "none" }because the bot listens on no port. Its only connection is the outgoing one to Discord."rollout": "recreate"stops the running container before the new one starts, so two copies of the bot are never logged in together."stopTimeout": 10gives the bot ten seconds afterSIGTERMto close its gateway connection, enough forclient.destroy().- The start commands run
node migrate.jsbeforenode bot.js. With one copy of the bot, the migration never runs twice at the same moment.
DISCORD_TOKEN is declared as a secret, so the deploy asks for it and it stays out of the repository. DATABASE_URL is the connection string of the main-db database. Save the file at the project root and commit it:
{
"$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1",
"resources": {
"bot": {
"type": "service",
"image": "node-22-slim",
"build": { "commands": ["npm ci"] },
"start": { "commands": ["node migrate.js", "node bot.js"] },
"healthCheck": { "type": "none" },
"rollout": "recreate",
"stopTimeout": 10
},
"main-db": { "type": "postgres", "plan": "postgres-1gb" }
},
"env": {
"DISCORD_TOKEN": { "type": "secret" },
"DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" }
}
}Adjust the config for your project
- With TypeScript, build in the build commands and start the compiled file:
"build": { "commands": ["npm ci", "npm run build"] }and"node dist/bot.js"as the last start command. - Without a database, remove
main-dbandDATABASE_URL, and start the bot withnode bot.jsalone. - For Redis, add
"cache": { "type": "redis" }and aREDIS_URLvariable with"resource": "cache". MongoDB is created for the environment as a platform resource and reaches the bot asMONGODB_URI. - A bot written in Python with discord.py, or in any other language, runs from its own Dockerfile: set
"dockerfile": "Dockerfile"on the service and keep the health check, rollout and secrets as they are. Dockerfile services explains the rest. - To run two bots, or a bot with a small dashboard next to it, add each as its own service in the same file. A web dashboard keeps the default health check and rollout.
Check the build locally
Run the same commands Modelence runs, against a local PostgreSQL and your test bot. The migration should print Database is up to date, then the bot logs in:
npm ci
DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres node migrate.js
DISCORD_TOKEN=<test bot token> DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres node bot.jsDeploy
From the project directory, run:
npx modelence@latest deploy
The browser opens for you to sign in and choose or create the organization, app and environment. Paste the production bot's token when it asks for DISCORD_TOKEN, and pick the AWS region where the bot and its database will run. The command then uploads the project and follows the build. On the environment's Logs page you'll see Database is up to date, then Logged in as <bot name>.
Since the bot answers no web requests, detach the environment's URL under Domains in the dashboard, which leaves the bot running with no public address. Every app has a sandbox and a production environment: give the sandbox the test bot's token, and the two never answer the same commands.
Have a coding agent set it up
Paste Deploy using https://modelence.com/skill.md into Claude Code, Cursor or Codex inside the bot's project. The agent writes modelence.config.json with the worker settings above, checks the build and deploys, and hands control back to you to sign in and paste the token.
Production readiness
Run exactly one copy
Discord lets the same token log in more than once, and every logged-in copy receives every interaction. With two copies, both try to answer, one reply wins and the other fails with "Interaction has already been acknowledged", and messages the bot sends on its own go out twice. Keep the service at one container with rollout set to recreate, give each environment its own bot application, and stop a copy running elsewhere, such as on your laptop or another host, before the deploy.
Answer within three seconds
Discord shows "The application did not respond" if an interaction gets no answer within three seconds. A command that waits on a database query or an outside API should call await interaction.deferReply() first, which shows "thinking" for up to 15 minutes, and then send the result with interaction.editReply().
Log errors that happen outside commands
discord.js reconnects to the gateway on its own after network drops and Discord restarts, so a short gap in the logs is normal. Errors outside a command handler, such as a failed scheduled message, should be logged rather than lost: add client.on(Events.Error, console.error) and process.on('unhandledRejection', console.error) near the top of bot.js.
Plan for sharding at 2,500 servers
Discord requires a bot in 2,500 or more servers to split its gateway connection into shards. For a bot growing toward that, new Client({ intents, shards: 'auto' }) asks Discord for the recommended count and opens them all from one process, which carries a bot well past that point on a larger container. Very large bots move to discord.js's ShardingManager, which runs shards as child processes.
Watch the logs
Everything the bot writes to stdout and stderr shows on the environment's Logs page, so the Logged in as line confirms each deploy, and a line per command shows which ones people use. For metrics, add a telemetry resource and send OpenTelemetry data, as Deploy setup describes.
Modelence vs Railway, Render and Fly.io for Discord bots
Railway, Render and Fly.io come up most when people look for a host to keep a bot online. Each one can run a discord.js worker that never sleeps, and they differ mostly in how a worker is set up and billed. The numbers come from their own pricing pages and docs, checked in November 2026.
| Platform | How the bot runs | Pricing |
|---|---|---|
| Modelence | A service with no health check port and recreate rollouts, on AWS in 17 regions, with managed PostgreSQL, MongoDB and Redis | Free plan, then from $20 a month with $20 of usage included |
| Railway | A service with no public domain, which stays awake while it holds the gateway WebSocket | Free plan with $1 of usage a month after a trial; Hobby $5 and Pro $20 a month, billed by the minute |
| Render | A background worker, the service type for processes without a port | Workers have no free tier and start at $7 a month for 0.5 CPU and 512 MB |
| Fly.io | A Machine in an app with no services, which Fly Proxy doesn't stop | A shared-cpu-1x Machine with 256 MB costs $2.19 a month |
Railway and Fly.io are low-cost places to start a hobby bot, and Render's background workers make the worker model explicit. Modelence suits a bot that belongs to a product, for example with a database it shares with a web app, a dashboard as a second service, and a sandbox and production environment for the whole team. For more options, see Railway alternatives.
Next steps
Frequently asked questions
How do I host a Discord bot 24/7?
Run it on a server or cloud platform that keeps one process running without a browser tab or laptop open. On Modelence you describe the bot as a service with no health check and a recreate rollout in modelence.config.json, then run npx modelence@latest deploy. The bot runs as a container on AWS, comes back after each deploy with its gateway connection, and keeps its data in a managed database.
Why does my Discord bot reply twice?
Two copies of the bot are logged in with the same token, and Discord sends each of them every interaction and event. It usually happens when the bot still runs on your laptop or an old host after a deploy, or when a platform starts the new version before stopping the old one. Stop the extra copy, give local testing its own bot application, and use a rollout that stops the old container first, which is what recreate does on Modelence.
Does a Discord bot need a port or a web server?
No. A gateway bot opens an outgoing WebSocket to Discord and listens on no port, so it needs no HTTP server and no health check route. On Modelence that's a service with its health check set to none, and the environment's URL can be detached. Only bots that receive interactions through an HTTP endpoint instead of the gateway need a public URL.
Can I deploy a discord.py bot the same way?
Yes. A Python bot built with discord.py runs from a Dockerfile that installs its requirements and starts the bot. Set dockerfile on the service in modelence.config.json and keep the health check at none, the rollout at recreate and the token as a secret, as in this guide.
Should my bot register slash commands every time it starts?
No. Registered commands are stored by Discord, so registering them again on every start only uses up the daily limit of 200 new commands per server. Keep registration in a script such as deploy-commands.js and run it when commands or their options change. Register to one test server while you work, where updates show at once, and globally for production.
Can I host a Discord bot for free?
You can build and test the bot on Modelence's free plan. For a bot that people rely on around the clock, the Starter plan at $20 a month includes the same $20 as cloud usage, which covers a small always-on bot, and adds managed PostgreSQL and Redis.
How do I move a Discord bot from Railway to Modelence?
Add modelence.config.json with the bot's start command, set the health check to none and the rollout to recreate, and declare the same variables. Stop or remove the Railway service before you deploy, so only one copy is logged in, then run npx modelence@latest deploy and paste the token. If the bot uses a Railway database, export it with pg_dump and restore it into the managed PostgreSQL before starting the bot.
When does a Discord bot need sharding?
Discord requires sharding once a bot is in 2,500 servers, and recommends a shard count when the bot connects. In discord.js, the shards: 'auto' client option uses that count from a single process, and the ShardingManager spreads shards across processes for very large bots. Until then, one connection handles everything.