DEV Community

Samar Meena
Samar Meena

Posted on • Updated on

🤖 Creating discord bot client from scratch!

We learned in the previous post how to quickly set up a discord bot, now let's take a look at how to set it up from scratch with discord.ts (discordx).

I assume you have installed node.js before we begin.

Directory structure

Here is a quick look at how the directory structure will appear at the end of this tutorial.

root
|
|__ src
   |
   |__ commands
       |__ common.ts
   |
   |__ main.ts
|
|__ tsconfig.json
|__ package.json
Enter fullscreen mode Exit fullscreen mode

1. Initialize project

To initialize a node project, type npm init in your command prompt

> npm init
{
  "name": "demox",
  "version": "1.0.0",
  "description": "my discord bot",
  "main": "build/client.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "MIT"
}

> cd demox
Enter fullscreen mode Exit fullscreen mode

2. Install required packages

Run the following command to install the packages we need for our project.

> npm install discordx reflect-metadata discord.js
Enter fullscreen mode Exit fullscreen mode

Typescript needs to be installed as a development dependency since our project will use it.

> npm install --save-dev @types/node typescript
Enter fullscreen mode Exit fullscreen mode

Here is an example of a package file after running the above commands.

{
  "name": "demox",
  "version": "1.0.0",
  "description": "my discord bot",
  "main": "build/client.js",
  "scripts": {
    "build": "tsc",
    "start": "node build/client.js"
  },
  "author": "",
  "license": "MIT",
  "dependencies": {
    "discord.js": "^13.x.x",
    "discordx": "^6.x.x",
    "reflect-metadata": "^0.1.x"
  },
  "devDependencies": {
    "@types/node": "^16.x.x",
    "typescript": "^4.x.x"
  }
}
Enter fullscreen mode Exit fullscreen mode

3. Setup typescript

There are two ways to set up typescript

  1. run command npx tsc --init
  2. manually create tsconfig.json in root directory.

Right now we're going to choose option 2, but you can choose option 1 if you prefer

Create a file named tsconfig.json in your root directory and paste the following content into it.

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "ES2021",
    "noImplicitAny": true,
    "sourceMap": true,
    "strict": true,
    "outDir": "build",
    "emitDecoratorMetadata": true, // required
    "experimentalDecorators": true, // required
    "declaration": false,
    "importHelpers": true, // required
    "forceConsistentCasingInFileNames": true,
    "lib": ["ES2021", "esnext.asynciterable"],
    "moduleResolution": "node"
  },
  "exclude": ["node_modules"]
}
Enter fullscreen mode Exit fullscreen mode

4. Setup discord bot client

Once we have finished the important setup, we are ready to create our bot in the way we want. I will create a simple slash command today, so let's get started

  1. Make a source folder called src in root directory
  2. Make a file called client.ts in src folder
  3. Copy and paste the below content into client.ts.
import "reflect-metadata";
import { Client } from "discordx";
import { Intents, Message } from "discord.js";

const client = new Client({
  botId: "test",
  // prefix: "!",
  prefix: async (message: Message) => {
    return "!";
  },
  // glob string to load the classes
  classes: [`${__dirname}/commands/**/*.{js,ts}`],
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.GUILD_MEMBERS,
  ],
  silent: false,
});

client.on("ready", () => {
  console.log(">> Bot started");

  // to create/update/delete discord application commands
  client.initApplicationCommands();
});

client.login(process.env.BOT_TOKEN ?? "");
Enter fullscreen mode Exit fullscreen mode

Notes

  1. Classes parameter is a array of glob path, which holds all your commands or events, where each class is decorated by @Discord
  2. If you don't want console logs, set the silent parameter to true.
  3. The prefix parameter/resolver is used for simple commands such as !hello world
  4. You should import the reflect-metadata module in your main file, for reflection. Otherwise, decorators may not function properly.

to learn more visit here

5. Setup slash command

Now that we are all set, we can create the slash command

note: Ensure that all files are registered with classes in client.ts.

  1. Make a file called common.ts in src/commands/ folder.
  2. Copy and paste the below content into common.ts.
import { CommandInteraction } from "discord.js";
import { Discord, Slash } from "discordx";

@Discord()
abstract class AppDiscord {
  @Slash("hello")
  private hello(interaction: CommandInteraction) {
    interaction.reply(`:wave: ${interaction.user}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

6. Prepare bot to execute interactions

To execute any discord application command, we need to call client.executeInteraction. Without this step, commands will not be executed.

client.on("interactionCreate", (interaction: Interaction) => {
  client.executeInteraction(interaction);
});
Enter fullscreen mode Exit fullscreen mode

7. Build bot

We are now ready to build our bot and launch it.

> npm run build
Enter fullscreen mode Exit fullscreen mode

8. Setup bot token

Before we start our bot, we need to setup a bot token, if you don't have one yet, you can get one from the Discord developer portal.

Check out this guide for more information on adding the bot to your discord server before starting the bot. The bot must be added to the server with required permissions, otherwise the slash command will fail.

> set BOT_TOKEN="<your bot token>"
Enter fullscreen mode Exit fullscreen mode

9. Start your bot

Your bot is ready to go 🚀

> npm start
Enter fullscreen mode Exit fullscreen mode

10. Finally

The /hello slash command will appear in your discord server.

discord command


Reference

Need more help?

Join our discord server

Thank you

If there are any mistakes, I apologize, Next, we will learn how to create a slash command with options.

Top comments (0)