A quick guide on how to build and launch a Discord bot with Discord.js
By the end of this guide, you will have a Discord bot which will be able to respond to text commands, as well as an idea of how to implement more complicated and interesting features.
Prerequisites
- A machine with Node.js installed
- Some familiarity with JavaScript and Node.js
- A Discord account with 2FA enabled
- A Discord server in which you have admin privileges
- Create your application in the Developer Portal
- Go to https://discord.com/developers/applications and log in.
- Click New Application, give it a name, and hit Create.
- In the sidebar, select Bot and then Add Bot.
Under TOKEN, click Copy—you’ll need this in a sec.
Keep your token secret. Never commit it to a public repo!Set up your project files
In your discord-bot directory, create the following files:config.json
index.js
Create a config.json with your bot token and a command prefix:
{
"token": "YOUR_BOT_TOKEN_HERE",
"prefix": "!"
}
- Install and import Discord.js Run:
npm install discord.js
Then, in index.js, bring in Discord.js and your config:
const { Client, Intents } = require('discord.js');
const { token, prefix } = require('./config.json');
- Initialize your client In index.js, set up a client that listens for messages:
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]
});
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag}`);
});
This logs a confirmation when your bot comes online.
- Handle text commands Add a messageCreate listener to parse and respond to commands:
client.on('messageCreate', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content
.slice(prefix.length)
.trim()
.split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
message.channel.send('Pong!');
} else if (command === 'say') {
const text = args.join(' ');
if (!text) return message.reply('You need to tell me what to say!');
message.channel.send(text);
}
});
- Log in and run your bot At the bottom of index.js, add:
client.login(token);
Then, in your terminal start your bot:
node index.js
You should see Logged in as YourBotName
in your terminal.
- Invite your bot to your server
- Back in the Developer Portal, go to OAuth2 → URL Generator.
- Under SCOPES (the first section), check bot.
- Under BOT PERMISSIONS (the second), select the permissions your bot needs. For the above code, we should only need the "Send Messages" permission.
- Copy the generated URL, open it in your browser, and choose your server. Your bot will appear in your server’s member list.
Congratulations! You've now created a Discord bot!
Top comments (0)