Adding commands

Getting started

So our bot is working, but you can't really do anything with it. Let's start by adding a command!

Adding our first command

Let's create a simple command that just sums a list of numbers. We'll define it like so:

const { matchPrefixes } = require("@enitoni/gears")
const { Bot, Adapter, Command } = require("@enitoni/gears-readline")

const sumCommand = new Command()
  .match(matchPrefixes("sum "))
  .use(context => {
    const numbers = context.content.split(" ").map(n => Number(n))
    const summed = numbers.reduce((a, b) => a + b)


const adapter = new Adapter({})
const bot = new Bot({ adapter, commands: [sumCommand] })

bot.start().then(() => {
  console.log("Hello world!")

So, we define a matcher by calling .match() on the builder. Then we set some middleware for the command, using .use(). Now, if you run your code again, you should be able to type sum 4 4 and get 8 back in return.

Nice! You just defined your first command!

Adding another command

We'll add another command to make the bot even more feature fledged. Let's add another math related command, one multiplies the numbers instead. Define it like so:

const multiplyCommand = new Command()
  .match(matchPrefixes("multiply "))
  .use(context => {
    const numbers = context.content.split(" ").map(n => Number(n))
    const multiplied = numbers.reduce((a, b) => a * b)


Now add it to the command array in the bot, after the sumCommand.
Again, run your code and check that it's working. You should be able to type multiply 2 2 and get 4 in return.

Creating your first bot
Using middleware