0

I'm trying to create a Whatsapp Bot in Javascript running it with NodeJS. I've created a base class Command, that gets inherited by other Commands.

class Command {

    prefix = '';

    constructor(client) {
        this.client = client;
    }

    get prefix() {
        return this.prefix.toLowerCase();
    }

    stripMessage(message) {
        return message.body.toLowerCase().split(' ');
    }

    handle(message) {

    }
}

module.exports = Command;

The Price command extends the base Command class.

const api = require('../api');
const Command = require('./command');

class Price extends Command {

    prefix = '/price';

    constructor(client) {
        this.client = client;
    }

    handle(message) {
        let args = this.stripMessage(message);
        if (typeof args[1] !== 'undefined') {
            api.get('/api/price/', args[1], function(data) {
                if (!data.data.succeed) {
                    this.client.reply(message.from, 'Unknown ticker.', message.id.toString());
                } else {
                    let answer = " The price of " + args[1] + " is €" + data.data.eur;
                    this.client.reply(message.from, answer, message.id.toString());
                }
            });
        }
    }
}

module.exports.Price = Price;

In my main file I then create a new instance of the Price class and use the handle function to handle the incoming message.

let price = new Price(client);
price.handle(message);

I've noticed that removing the constructor in the Price class will stop breaking the code, however, the constructor I extend from my parent class doesn't get executed. I've created a constructor in the Command class, I assumed that when I create a new instance of Price the constructor of my parent gets called. That didn't work. The client was still undefined. I then added a constructor to Price to solve this problem, however that breaks the code.

Aziza Kasenova
  • 1,501
  • 2
  • 10
  • 22
Esmay Kapol
  • 231
  • 3
  • 12
  • 6
    It should be `constructor(client) { super(client); }` – blex Mar 21 '21 at 10:05
  • I've tried that aswel. But I still get the message that client is undefined. – Esmay Kapol Mar 21 '21 at 10:07
  • 1
    Oh ok, you are also calling `this.client` inside `api.get('/api/price/', args[1], function(data) {...`. The context is lost. Replace `function(data) {...}` with `(data) => {...}` [More info](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable) – blex Mar 21 '21 at 10:10
  • 1
    You are a hero! @blex Worked like a charm. Didn't knew it could only be how I defined a function. – Esmay Kapol Mar 21 '21 at 10:13

0 Answers0