My journey with Discord bots from Java to Node.js — Part 2 Developing the bot

Amr Gawish
kblog
Published in
2 min readApr 27, 2017

--

Continuing my journey from Part 1, after having a not-so-bad project structure, I needed to make sure I’m being totally DRY and using the best practice of Node.JS!

Table of Content

Defining the Service Layer

In my previous article I decided to create a service layer, each service would consume a specific RESTful APIs source. I used 3 services: Bungie, GuardianGG and DestinyTrialsReport.

So I created 3 service files, since I’m using Node.JS version 6, I opted to use the best practice for ES6, which has definition for Classes and has a much cleaner syntax.

I also avoided using var and opted to use let and const instead, this made my life a little bit easier.

Here is how my Bungie Service looks

As you can notice, I felt right at home with that new structure, since Classes is the main construct in Java and this structure looks very familiar.

Organising different Bot commands

In order to optimize the registry of different commands for my bot, I used a CommandRegistry to register different commands — I later discovered that it exist as part of core Discord.js library — so I can do something like the following:

The registry is a simple regex — It can capture spaces within quotes as a single entity — and calls the callback method (second-argument) when the message issued a command. It also works on Mention only, so you need to mention the bot in Discord for this to trigger, which was my use case.

My CommandRegistry class was following the below structure:

I also had a list of commands since I can listen to the wildcard, but needed to make sure it’s not being called when another command is there.

Also I replaced the previous structure from Listeners to Commands and opted for the below structure:

├───lib/
│ └───services/
│ └───bungie.service.js
│ └───commands/
│ └───command.js
│ └───command.registry.js
│ └───help.command.js
├───conf/
│ └───config.js
├───app.js
├───package.json

So the last piece of work I needed to do is to create my commands, so for Instance the help.command.js looked like

Note that I used inheritance here, since I have multiple commands, and I wanted to reuse as much parts as I can.

Conclusion

I was pretty happy with the architecture and everything worked out pretty well for me, and I think it can be easily understood and navigated.

The only thing missing for me is to actually deploy the application and see its fruit in action.

In the next and final article I’m going to talk about that process.

--

--

Editor for

A father, Gamification advocate, and a fellow software craftsman!