let's learn how to make a simple Discord bot with Node.js. This tutorial aims at beginners with zero knowledge on how to make a Discord bot.
- Code editor (i.e. VS Code)
- Basic knowledge in JavaScript
- Node and npm installed in your machine
- A Discord account and server set up
-
First, we need to create a discord bot as an app in Discord. Go to https://discord.com/developers and sign in or create a developer account.
-
Once you're logged in, click on
New Application
at the top right of the window.
- Then you can create your app using fill in the details example name of bot etc and you will be taken to your app's dashboard. Navigate to
Bot
and clickAdd Bot
to enable your app as a bot.
- Go to to the bot section and enable the Bot app option for the app.
- Click Yes and go to the Bot details page.Now, you'll have your bot and see this section appear.
Click on 'Copy' to copy your token and save it somewhere, we'll need it for later.This is very secret token please dont publish anywhere.
- Go to the OAuth2 section and Select bot under the scope section.
- Also, give permission to your bot for you need basis.
- Now showing the link of your bot Like This Link:-
- Copy this URL and paste it on a new tab. You will be redirected to the page as shown below:
-
Install this bot to your preferred Discord server. For example, mine is the
CryptoDeveNepal
server I just created. -
If everything works correctly, your bot should now appear in your Discord server.
- Now our CryptoBotNp is live into server
Now let's make this bot work! Create a new project with the following terminal commands:
mkdir discordBot
cd discordBot
npm init
Now we need to install the npm packages for this project. Run this command below:
npm install discord.js axios dotenv
The packages we have installed are:
- discord.js: a Node.js module to allow easy interactions with the Discord API.
- axios: allows making HTTP Promises easily with Node.js.
- dotenv: allows loading variables from process.env in Node apps
This will create an index.js file, where our bot functions will be written at.
If you see the bot installed in your server, it is currently offline. The first thing we need to do to code our discord bot is to create a discord bot client and log our bot in.
Import the discord.js package and create a new client like so:
Remember the token we copied in Step 1? Create an .env file and store the token there.
In your .env file:
- CLIENT_TOKEN=
'your token here'