🤖 Creating discord bot client from scratch!
Vijay Meena
Posted on August 26, 2021
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
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.
{
"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
- run command
npx tsc --init
- 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"]
}
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
- Make a source folder called
src
in root directory - Make a file called
client.ts
insrc
folder - 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 ?? "");
Notes
- Classes parameter is a array of glob path, which holds all your commands or events, where each class is decorated by
@Discord
- If you don't want console logs, set the
silent
parameter to true. - The
prefix
parameter/resolver is used for simple commands such as!hello world
- 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
.
- Make a file called
common.ts
insrc/commands/
folder. - 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: </span><span class="p">${</span><span class="nx">interaction</span><span class="p">.</span><span class="nx">user</span><span class="p">}</span><span class="s2">
);
}
}
- 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);
});
- Build bot
We are now ready to build our bot and launch it.
> npm run build
- 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>"
- Start your bot
Your bot is ready to go 🚀
> npm start
- Finally
The /hello slash command will appear in your discord server.
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.
Posted on August 26, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.