A
A
anamorph2017-03-13 14:38:00
JavaScript
anamorph, 2017-03-13 14:38:00

Is it possible to access a variable inside a function, or how else to solve the problem?

I create a telegram bot on node js
, there is an array with Arr objects, and the getRandomObj function, which returns a random object from this array,
in theory, the bot displays a message, the timer should immediately start,
then the person presses the button either ready or canceling, depending on what will be apply further actions

bot.onText(/\/go/, function(msg, match) {
  var obj= getRandomObj();
    id = msg.chat.id;
    title = obj.title;
    time = obj.time;

  var message = title + ' for ' + time/1000/60 + ' mitute.';

  var options = {
    reply_markup: JSON.stringify({
        inline_keyboard: [
          [{ text: 'Готово!', callback_data: 'done' }],
          [{ text: 'Отменить', callback_data: 'reject' }]
        ]
      })
  };
  bot.sendMessage(id, message, options);
});

there's just a problem. Where to put the timer?
var timerId = setTimeout( function(){
  bot.sendMessage(id, 'time is over!');
}, time)

the matter is that time the timer should receive from that object which comes after the getRandomObj function. The message is also formed from it.
If you insert this function into bot.onText, then everything works, but only when it comes to callbacks, and this:
bot.on('callback_query', function(cb) {
  if (cb.data === 'done') {
    //тут надо остановить таймер
    bot.sendMessage(id, 'done');
  } else{
                //и тут
    bot.sendMessage(id, 'отклонено');
  }
});

I can’t pass timerId to this function to stop it.
And if I insert it into bot.onText, then the timer stops, but the message is displayed not once, but first 1 time, then 2, then 3 times, etc.
help me figure it out problem and suggest solutions to it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Anton, 2017-03-13
@Fragster

you can shove the id of the timers into the global hash array with the chat key. well, or some other "sessions" to fasten, if the library supports. telegraf seems to support

T
tagplus5, 2017-03-14
@tagplus5

You need to use session. For example, like here: telegraf.js.org/introduction.html#session

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question