🤖 Creating discord bot client from scratch!
Tags: typescript, javascript, tutorial, discord
Published: 2021-08-26 12:32:26

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)](https://www.npmjs.com/package/discordx).

I assume you have installed [node.js](https://nodejs.org/en/) 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
```

___

### 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
```

### 2. Install required packages

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

```
> npm install discordx reflect-metadata discord.js
```

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

```
> npm install --save-dev @types/node typescript
```

Here is an example of a package file after running the above commands.
```json
{
  "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"
  }
}
```

### 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.

```json
{
  "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"]
}
```

### 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``.

```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 ?? "");
```

**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](https://oceanroleplay.github.io/discord.ts/docs/general/client)

### 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``.

```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}`);
  }
}
```

### 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.

```ts
client.on("interactionCreate", (interaction: Interaction) => {
  client.executeInteraction(interaction);
});
```

### 7. Build bot

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

```
> npm run build
```

### 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](https://discord.com/developers/applications).

[Check out this guide](https://oceanroleplay.github.io/discord.ts/docs/decorators/commands/slash#authorize-your-bot-to-use-slash-commands) 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>"
```

### 9. Start your bot

Your bot is ready to go 🚀

```
> npm start
```

### 10. Finally

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

![discord command](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ulnu2xmdgk0wa9q0zooa.png)

___

## Reference
* [discordx](https://www.npmjs.com/package/discordx)
* [starter project](https://github.com/oceanroleplay/discord.ts-example)
* [documentation](https://oceanroleplay.github.io/discord.ts/)
* [github](https://github.com/oceanroleplay/discord.ts)

## Need more help?
Join our [discord server](https://discord.gg/yHQY9fexH9)

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