Learning objectives
After reading this article you will be able to:
- Create the app and the bot token in the Discord Developer Portal
- Write, register and test a slash command with discord.js
- Put the bot online and confirm it is running
On this page
- What do you need before you start?
- How do you create the app and the token in the Portal?
- How do you set up the project?
- How do you write the bot code?
- How do you register and test the slash command?
- What errors show up with a first bot?
- How do you keep the bot online all the time?
- How to do this on Square Cloud
- FAQs
A Discord bot is a program that connects to Discord with a token and reacts to events: a typed command, a message, a member joining. It does not live inside Discord. It runs on your computer or on a server, so it is only online while that process is running.
Making your first bot has two parts: setting up the app in the Developer Portal and writing the code. This guide covers both and ends with the bot online, using JavaScript with discord.js v14, the most widely used library for the job.
What do you need before you start?#
- A current Node.js version. The official discord.js guide recommends the current Active LTS of Node.js; the official release schedule shows which one that is. Check yours with
node --version. - A Discord account and a server of your own for testing. To invite a bot you need the Manage Server permission there.
- A text editor and a terminal.
How do you create the app and the token in the Portal?#
- Open the Discord Developer Portal and click New Application. Name it and confirm.
- On the app page, copy the Application ID (General Information tab). This is your
CLIENT_ID. - Open the Bot tab and click Reset Token. Copy the token right away, because it is shown only once. If you lose it, generate another.
- Don't confuse the token with the client secret: the secret is a shorter string and won't work for the bot.
The token is the bot's password: whoever has it controls the bot. Never put it in your code or in a repository. The article on the Discord bot token covers how to store it and what to do if it leaks.
For the GUILD_ID, turn on Developer Mode under User Settings, Advanced. Then right-click your server icon and choose the option to copy its ID (Discord support has the full steps).
How do you invite the bot to your server?#
In the Portal, open OAuth2 and use the URL generator:
- Select the bot and applications.commands scopes.
- Choose the permissions the bot needs. The
/pingcommand in this guide needs none. - Copy the generated URL, open it in your browser and pick your test server.
The bot shows up in the member list as offline. It only goes online once the code is running.
How do you set up the project?#
Create the folder, install the library and enable ES modules in package.json:
mkdir my-bot && cd my-bot
npm init -y
npm pkg set type=module
npm install discord.jsCreate a .env file next to package.json and add .env to .gitignore:
DISCORD_TOKEN=paste_the_token_here
CLIENT_ID=application_id
GUILD_ID=test_server_idNode.js reads this file with the --env-file flag, no extra package needed, as the Node.js documentation shows.
How do you write the bot code?#
Create index.js. The bot uses only the Guilds intent, which is enough for slash commands, and answers /ping:
import { Client, Events, GatewayIntentBits } from "discord.js";
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.once(Events.ClientReady, (readyClient) => {
console.log(`Online as ${readyClient.user.tag}`);
});
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === "ping") {
await interaction.reply("Pong!");
}
});
client.login(process.env.DISCORD_TOKEN);The structure follows the official discord.js guide: create the client, log when it connects, listen for interactions and log in with the token.
How do you register and test the slash command?#
Writing the if for /ping does not create the command in Discord. You must send its definition to the API once, and again whenever it changes. Create deploy-commands.js:
import { REST, Routes, SlashCommandBuilder } from "discord.js";
const commands = [
new SlashCommandBuilder().setName("ping").setDescription("Replies with Pong!"),
].map((command) => command.toJSON());
const rest = new REST().setToken(process.env.DISCORD_TOKEN);
await rest.put(
Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID),
{ body: commands },
);
console.log(`${commands.length} command(s) registered.`);For testing, register commands on your server only. The discord.js guide notes there is a daily limit on command creation, so do not register on every bot start. Once the commands are final, switch the route to Routes.applicationCommands(process.env.CLIENT_ID) so they apply to every server.
How do you test the bot locally?#
Register the command and start the bot:
node --env-file=.env deploy-commands.js
node --env-file=.env index.jsThe terminal should print Online as BotName, and the bot goes online in your server. Type /ping and check for the Pong! reply.
What errors show up with a first bot?#
Error [TokenInvalid]: An invalid token was provided.: the token is empty or wrong. Check that.envis in the right folder, that you passed--env-file=.envand that you did not copy the client secret.- The command does not show in Discord: you did not run
deploy-commands.js, theGUILD_IDbelongs to another server, or the invite lacked theapplications.commandsscope. Integration requires code grant(older guides showBot requires a code grant): turn off the Requires OAuth2 Code Grant option in the Portal's Bot tab.Used disallowed intents: the code asks for a privileged intent that is not enabled in the Portal's Bot tab.- The bot goes offline when you close the terminal: that is expected. The process must run on a machine that stays on.
If the bot is online but does not answer, see Discord bot not responding.
How do you keep the bot online all the time?#
Your computer is fine for development, but the bot goes down whenever the computer shuts off or loses its connection. There are two paths to a 24/7 bot:
- VPS: you install Node.js, set up a supervisor such as pm2 or systemd, and handle updates and firewall. The steps are in how to keep a bot online 24/7.
- Bot hosting platform: you upload the code and set environment variables; the Node.js environment already exists.
To estimate your bot's memory, see how much RAM a bot needs. The full hosting process is covered in how to host a discord.js bot.
How to do this on Square Cloud#
On Square Cloud, the bot runs in an isolated, always-on container, with automatic restart (on by default for dashboard deploys) when the process exits with an error. You deploy it with a ZIP upload in the dashboard, the CLI, GitHub or the VS Code extension.
- Zip the project with
index.jsandpackage.jsonat the root of the ZIP, without.envand withoutnode_modules(at start, the platform runsnpm install). - Upload it in the dashboard. The
squarecloud.appfile is optional: the dashboard generates it with the runtime, memory and main file, or you can write it at the project root. - Choose the Node.js runtime and
index.jsas the main file. Each background application, such as a bot, uses at least 256 MB from the plan's RAM pool. - Set
DISCORD_TOKENin the application's environment variables. The change takes effect on the next restart. - Run
deploy-commands.jsonce on your computer, as before, and watch the live logs untilOnline as ...appears.
Plans are paid: Hobby, at R$12.49 per month, includes 1 GB of RAM and 1 vCPU. See the details in Discord bot hosting on Square Cloud.
Bot hosting
Keep your bot online 24/7 with automatic restarts
FAQs
Do I need to know how to code to make a Discord bot?
Yes, the basics. This guide uses JavaScript with Node.js and about 30 lines of code across two files. If you can run a file with Node.js and edit text, you can follow along.
Which language should I use for a first bot?
JavaScript with discord.js and Python with discord.py are the most common choices, with the most complete documentation. Pick the one you already know, since the Portal steps are the same.
Why is my bot online but the command does not show up?
Starting the bot does not create slash commands. They must be registered with the Discord API using a separate script, and the bot must have been invited with the applications.commands scope.
Does the bot need privileged intents?
Not for slash commands. The Guilds intent is enough. Privileged ones, like MessageContent, are only needed to read the text of regular messages and must be enabled in the Portal.
More in Bots
See all 33 articles- How much does it cost to host a Discord bot?The cost of hosting a Discord bot depends on RAM, uptime, database and outside services. Learn how to estimate your own bill and where the money goes.
- Running a bot on your phone or PC vs hosting itA bot on your PC or phone (Termux) goes offline when the device shuts down, sleeps or loses its network. Compare the three options and when each one fits.
- How to host a Discord bot 24/7To keep a Discord bot online 24/7, run its process on an always-on machine with automatic restarts. Compare your PC, a VPS with pm2 or systemd, and bot hosting.
- Why your Discord bot keeps going offline (and how to fix it)A Discord bot goes offline when the process dies, the token is invalid, an intent is disabled or memory runs out. Learn to diagnose each cause and fix it.