yagop / node-telegram-bot-api

Telegram Bot API for NodeJS
MIT License
8.45k stars 1.53k forks source link

How to manage updateSubTypes in multiple messages #799

Closed paulbraam closed 4 years ago

paulbraam commented 4 years ago

Hi,

I was using the code from #192 like this:

const Promise = require('bluebird');

function sendMessages(bot, chatId, messages) {
    return Promise.mapSeries(messages, function(message) {
        return bot.telegram.sendMessage(chatId, message);
    });
}

But what if I would like to send multiple messages that contain not only text, but also audio and photo updateSubTypes?

Here's what I tried to do, but it didn't work:

const Promise = require('bluebird');

function sendMessages(bot, chatId, messages) {
    return Promise.mapSeries(messages, function(message) {
      if (message.updateSubTypes === 'text') {
        return bot.telegram.sendMessage(chatId, message);
    } else if (message.updateSubTypes === 'audio') {
      return bot.telegram.sendAudio(chatId, message);
  }
  })
}

Please suggest how to implement this.

kamikazechaser commented 4 years ago

Approach is okay, but use Promise.all() instead of bluebird.

A simple example would be:

const textMessage = bot.sendMessage(chatId, 'hello');
const image = bot.sendPhoto(chatId, 'someImageUrl');
const anotherTextMessage = bot.sendMessage(chatId, 'world');

Promise.all([textMessage, image, anotherTextMessage]).then((res) => {
  console.log('messages sent');
});

This does not guarantee order in which the messages are sent. You can ensure ordered sending with something like Array.reduce(). Here is an article on it.

So you would do something like:

return [textMessage, image, anotherTextMessage]
  .reduce((promiseChain, currentTask) => {
    return promiseChain.then((chainResults) =>
      currentTask.then((currentResult) => [...chainResults, currentResult])
    );
  }, Promise.resolve([]))
  .then((arrayOfResults) => {
    console.log(arrayOfResults);
  });

There are more hipster approaches to reduce lines of code to send out sequentially. You could google them.