Documentation / Learn to write a bot / Write your first bot
- Create the application
Create a new application in the Discord Developer Portal and get the token from the Bot tab.
- Set up the project
Run npm init -y and npm install discord.js dotenv in a folder.
npm install discord.js dotenv - Run it
Write the index.js file and start it with node index.js.
node index.js
By the end of this lesson you will have a bot that shows up online in your own server. Do each step in order; if you skip one, the next will not work.
1. Install Node.js
Download and install the LTS version from nodejs.org. After installing, open the terminal (PowerShell on Windows) and check the version. discord.js v14 needs Node.js 18 or newer.
node -v
# should print something like v22.x.x2. Create an application on Discord
Go to discord.com/developers/applications and create an application with New Application. Then:
- Bot tab
- Press Reset Token and copy the token. The token is your bot's password; never share it.
- Privileged Gateway Intents
- Turn on Message Content Intent if you want to read message content, and Server Members Intent if you will track member joins.
- Application ID
- You will need this number from the General Information tab when registering commands.
3. Invite the bot to your server
In the URL Generator under the OAuth2 tab, pick bot and applications.commands under scopes and tick the permissions you need. Open the generated link in your browser and pick your test server.
- While learning, create an empty test server for yourself so your real server is not affected by the bot's mistakes.
4. Set up the project
Create a new folder on your computer and open the terminal in that folder:
mkdir my-bot
cd my-bot
npm init -y
npm install discord.js dotenvnpm init starts the project (package.json is created); npm install downloads the libraries (the node_modules folder).
5. Keep the token safe
Do not write the token in your code. Create a file named .env in the folder and put the token there. dotenv reads this file and loads it into process.env. If you will put the code on GitHub, do not forget to add .env to your .gitignore file.
TOKEN=your-bot-token-here
CLIENT_ID=application-id
GUILD_ID=your-test-server-id6. First code: index.js
Create an index.js file in the folder, write the code below and run node index.js in the terminal. If you see "online" in the terminal, your bot shows the green dot on Discord.
require("dotenv").config();
const { Client, Events, GatewayIntentBits } = require("discord.js");
// Intents: which events the bot receives. For now, only server information.
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.once(Events.ClientReady, (c) => {
console.log(`Online as ${c.user.tag}!`);
});
client.login(process.env.TOKEN);Press Ctrl + C in the terminal to stop the bot.
- If you get a "Used disallowed intents" error, you have not turned on that intent in the Developer Portal.