DEV Community

0xkoji
0xkoji

Posted on • Edited on

Create Hello World Discord Bot with discord.js

A couple of days ago I created a new Discord server(This is the first time to create it) to communicate with school alumni.

I just tested discord.js since I may need to create a bot for the Discord server to do something.

In this post, I will show you how to create a Hello World bot that I post hello and a bot replies world to a channel.

Discord developer portal

https://discord.com/developers/docs/intro

discord.js

https://discord.js.org/#/

Step 1 Set up a bot

discord.py has a good page for this step.
https://discordpy.readthedocs.io/en/stable/discord.html

Step 2 Create a project

discord.js requires node 16.6.0+

$ yarn init -y
# if you use npm
$ npm init -y
Enter fullscreen mode Exit fullscreen mode

install packages
If you would like to use js, skip yarn add -D/npm install -D.
In addition, dotenv is optional. If you want to test discord.js quickly, you won't need to install dotenv and you will need to hardcode the Token

$ yarn add discord.js dotenv
$ yarn add -D typescript ts-node
# for npm
$ npm install discord.js dotenv
$ npm install -D typescript ts-node
Enter fullscreen mode Exit fullscreen mode

Step 3 Write a hello world bot

if you use js, you need to use require instead of import;

.env

TOKEN=xxxxxxx your token xxxxxxxxx
Enter fullscreen mode Exit fullscreen mode
import DiscordJS, { Intents } from "discord.js";
import dotenv from "dotenv";
dotenv.config();

const client = new DiscordJS.Client({
  intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});

console.log("Starting...");

client.on("ready", () => {
  console.log(`the bot is online!`);
});

client.on("messageCreate", (message) => {
  console.log("messageCreate");
  // get author info
  const authorId = message.author.id;
  const authorName = message.author.username;
  console.log(`author: ${authorName}`);
  if (message.content === "hello") {
    message.reply({content: "world"});
  }
});

client.login(process.env.TOKEN);
Enter fullscreen mode Exit fullscreen mode

Step 4 Try a bot

run the bot

$ ts-node index.ts
# if you use js
$ node index.js
Enter fullscreen mode Exit fullscreen mode

Post something to a channel. If you post hello, the bot replies world. At the same, time you can see your account name and your account id in your terminal.

Top comments (0)