A
A
Artem2018-07-16 16:43:00
API
Artem, 2018-07-16 16:43:00

How to properly handle events in node-telegram-bot-api?

Immediately code:

import TelegramBot from 'node-telegram-bot-api';

const bot = new TelegramBot('123456789', { polling: true });

bot.onText(/\/start/, function (msg) {
  
  let startMessage = 'Приветствие';

  let keyboard = {
      reply_markup: {
        inline_keyboard: [
          [
            {
              text: 'Создать напоминание',
              callback_data: 'newNote'
            },
            {
              text: 'Мои напоминание',
              callback_data: 'myNotes'
            }
          ]
        ]
      }
  };

  bot.sendMessage(msg.chat.id, startMessage, keyboard);

});

bot.on('callback_query', (query) => {
  
  let id = query.message.chat.id;

  switch (query.data) {
    case 'newNote':
      bot.sendMessage(id, 'Введите напомнинание');
      
      bot.on('message', (msg) => {
        bot.sendMessage(id, `Ок, напомню ${msg.text}`);
      });
      break;
    case 'myNotes':
      bot.sendMessage(id, 'Здесь будут Ваши напомнинания');
      break;
  }

})

The problem is this, I click /startand I have a greeting and 2 inline buttons: "Create a reminder" and "My reminders", if I click create, he will ask what exactly to remind and I will write some text, in response I will receive "ok, I will remind you. .." and once again if I write some text, he will also answer "ok, I'll remind you (what I wrote)" and if I click "My reminders" it will give me a list of my reminders and in theory what I will write next he should not create reminders and write like "ok, let me remind you ..." but he writes anyway, so how can you avoid this?
I am new to this business, and if someone has the opportunity, I would like, periodically, directly to ask questions, to consult.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2018-07-16
@itwaze

Briefly:
Take telegraf and see this section
More detailed:
You need to store the "state" of the user somewhere. For example, in a database or Redis. And then the code will be something like this:

bot.on('message', msg => {
     const session = getSessionFromDb(msg.from.id)
     if (session === 'foo') { //пользователь уже ввёл напоминание
         //обрабатываем одним способом
     } else if (session === 'bar') { //пользователь не ввёл 
        //обрабатываем другим способом
     }
})

Extended:
Read about the finite state machine. Its essence is that it returns different values ​​for the same input data depending on the state in which it is located. This is described in detail in Wikipedia.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question