
Crafting Your First Discord Bot: A Step-by-Step Guide
4 October, 2023
5
5
2
Contributors
Hey developers! Want to create your first discord bot using discord.js? Look no further This article is your gateway to crafting your own Discord bot buddy. So, fasten your seatbelt and let's dive into it.
1. Crafting the key🗝️
i) Set up a Discord account
Before creating a bot, you need to have a Discord account. If you don't have one, sign up at Discord's website.
ii) Navigate to the Discord Developer Portal
- Go the the discord developer portal.
- Log in with your Discord account.
iii) Create a New Application
- Click on the "New Application" button.
- Give your application a name. This doesn’t have to be the name of your bot, it’s just the name of the application.
- Click on "Create" after you've entered a name.
iii) Set up a Bot User
- You can set an image for your bot and modify its name in the "Bot" section.
- In the bot's username section, there's a "Reset Token" button. Press this button to produce the crucial bot token needed to operate your bot. Treat this token like a password; never share it with anyone.
- Also, if you scroll further in the bot section, you can turn on certain settings to prevent future issues and press the save changes button.
iv) Invite your Bot to a Server
- Go to the "OAuth2" tab in the Developer Portal.
- Under the "OAuth2 URL Generator", check the "bot" scope. This tells Discord you're adding a bot.
- Below that, a "BOT PERMISSIONS" section will appear. Choose the permissions your bot needs. In my case, I tick the Administrator option for educational purposes (In general, To avoid the error related to permission)
- Copy the generated URL and paste it into your browser.
- You'll be prompted to select a server to invite your bot to. Choose the appropriate server and complete the verification steps.
That's It, We have finally created the token!
Now your bot should be in the server, but it's offline. To make it functional, you'll need to use your bot token (from Step 3) in your bot's code to authenticate and interact with the Discord API.
2. Setting Up the Stage 🎭
Before the show begins, Let's prepare our backstage. Ensure you have Node.js and npm(Node package manager) installed. If not grab them from the official website Once you have them, you're good to roll.
- Node js: Download
3. Making the Magic Potion 🧪
Let’s initialize our project:
mkdir my-discord-bot
cd my-discord-bot
npm init -y
This will whip up a package.json
file which is like a recipe card for your project.
Additionally, Add the following code in your package.json file to use es6 javascript.
"type":"module";
4. Summoning the Main Ingredient 📘
You guessed it right! It’s the discord.js
library. Discord.js is one of the popular libraries for interacting with the discord API, allowing developers to create and manage their custom discord bots using JavaScript.
Add it to your mix by:
npm install discord.js dotenv nodemon
dotenv
for storing the discord bot token in .env file
nodemon
for starting the bot.js
After the installation, Setup the nodemon through package.json like this:
{
"name": "my-discord-bot",
"version": "1.0.0",
"description": "",
"main": "bot.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon bot.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"discord.js": "^14.13.0",
"dotenv": "^16.3.1",
"nodemon": "^3.0.1"
}
}
5. Scripting the Spell 🪄
In the root of your project, create a file named bot.js
. Here, we will script our bot's magic. Start with the basics:
import { Client, GatewayIntentBits } from "discord.js";
import { } from "dotenv/config";
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.MessageContent,
],
});
client.once("ready", () => {
console.log("Logged in as " + client.user.tag);
});
client.login(process.env.DISCORD_BOT_TOKEN);
Remember to create the .env file and store the bot token in
DISCORD_BOT_TOKEN
That we created earlier in this blog But guard this token as you would do for treasure because, with it, someone can control your bot.
6. Awaken Your Creation 🤖
Simply run:
npm start
If the stars align, you’ll see the message Logged in as [YOUR_BOT_NAME]
in your terminal.
7. Add some powers🔥
So, you've got a basic bot. Now, let's add a new feature to it: a command that gives you details about your server. Here's how you can add a !serverstats
command to your bot.
Code:
import { Client, GatewayIntentBits } from "discord.js";
import {} from "dotenv/config";
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.MessageContent,
],
});
client.once("ready", () => {
console.log("Logged in as " + client.user.tag);
});
client.on("messageCreate", async (message) => {
if (message.author.bot) return;
if (message.content === "Hi") {
message.reply(`Hello **${message.author.username}**!`);
}
if (message.content.toLowerCase() === "!serverstats") {
const guild = message.guild;
message.channel.send(
`\`\`\`Server name: ${guild.name}\nTotal members: ${guild.memberCount}\nCreated at: ${guild.createdAt}\`\`\``
);
}
});
client.login(process.env.DISCORD_BOT_TOKEN);
Explaining the Code:
- Setting Up: We get the tools we need: the Discord library and environment variables.
- Starting the Bot: The
client.once("ready", ...)
part just lets us know our bot has started correctly. - Checking Messages: The bot looks at each message in your server to see if it should do something.
- If the message is from another bot, it ignores it.
- If someone says "Hi", it replies with "Hello" and their username.
- If someone types
!serverstats
, the bot will send a message showing the server's name, total members, and the date it was created.
- Logging In: The last line logs the bot into Discord using a secret token.
And that's it! You've added a new feature to your bot. Now, when you type
!serverstats
in your server, your bot will tell you some info about the server. Cool, right?
Fingers crossed! Let's boot up the bot and see the bot in action.
Run:
npm start
Spell works:
Now, See the magic:
8. End Note 📜
As our journey progresses, remember,with great power comes great responsibility. Always respect the privacy of your server members and ensure your bot operates within the boundaries of Discord’s rules.
Keep experimenting, keep exploring, and keep coding. The realm of Discord Bots is vast, and the magic is limitless.
Happy coding, sorcerers! 🌟🎩
This is the submission for the development track.
Thank you for the awesome event ShowwcaseHQ.
#writetowin #showwcase
showwcase
writetowin