Как выйти из обработчика сообщений в telegram bot?

Здравствуйте. Решил начать изучать ка писать ботов для telegrama и столкнулся с проблемой.
Пишу пока простенькое приложение для показа погоды.
Вот index.js:
const bot = require('./bot');
const Controller = require('./controller');

bot.onText(/\/start/, msg => {
    let controller = new Controller(msg);

    controller.start();
});

bot.onText(/\/weather/, msg => {
    let controller = new Controller(msg);

    controller.weather();
});

Вот bot.js:
const TelegramBot = require('node-telegram-bot-api');

const token = '';

const bot = new TelegramBot(token, {
    webHook: {
        port: process.env.PORT || 5000
    }
});

bot.setWebHook();

module.exports = bot;

Вот controller.js
const request = require('request');
const cityToCoords = require('city-to-coords');
const bot = require('./bot');

class Controller {
    constructor(msg) {
        this.msg = msg;
    }

    get userId() {
        const {
            from: {
                id
            }
        } = this.msg;

        return id;
    }

    get userFirstName() {
        const {
            from: {
                first_name
            }
        } = this.msg;

        return first_name;
    }

    get userLastName() {
        const {
            from: {
                last_name
            }
        } = this.msg;

        return last_name;
    }

    get userUsername() {
        const {
            from: {
                username
            }
        } = this.msg;

        return username;
    }

    get chatId() {
        const {
            chat: {
                id
            }
        } = this.msg;

        return id;
    }

    start() {
        bot.sendMessage(this.userId, `Welcome, ${this.userFirstName}`);
    }

    weather() {
        bot.sendMessage(this.userId, 'Where do you want to know the weather forecast?')
            .then(() => {
                this.onText(/(.+)/, msg => {
                    return console.log(msg);
                });
            });
    }
}

module.exports = Controller;


Проблема вот тут:
bot.sendMessage(this.userId, 'Where do you want to know the weather forecast?')
   .then(() => {
       this.onText(/(.+)/, msg => {
             console.log(msg);
       });
  });

Я хочу спросить у пользователя для какого города он хочет просмотреть погоду. И потом что бы я не вводил оно все время возвращает console.log(msg). Как можно это модифицировать что бы этого не было. Спасибо
  • Вопрос задан
  • 1098 просмотров
Решения вопроса 1
dummyman
@dummyman
диссидент-схизматик
Необходимо обозначить регулярку как значение переменной чтобы использовать несколько раз. Каждое последующее использование метода onText() с тем же параметром регулярки отменяет прошлый обработчик.
var rx=/(.+)/;
var emptyFn=function(){};
bot.sendMessage(this.userId, 'Where do you want to know the weather forecast?')
   .then(() => {
       this.onText(rx, msg => {
             console.log(msg);
             this.onText(rx, emptyFn);
       });
  });
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы