0

Here is my piece of code:

let interval = chatType === 'private' ? 1000 : 5000; 
        let it = 0;
        dl.imgs.forEach(function (el, index) {
            it += interval * index;
            if (index===2) it += 60000;
            setTimeout(function () {
                console.log(`part #${index+1}; size=${el.length}; timeout=${it}`)
                bot.sendMediaGroup(chatId, el, { reply_to_message_id: userMsgId, disable_notification: true, allow_sending_without_reply: true }).catch((err) => {
                    console.log(err.code);
                    console.log(err.response.body);
                });
            }, it);
        });

As far as I know, the limits is 20 messages per minute in one group (for private chats limits are different, so I hadle it firstly). And for sendMediaGroup each item counts as a separate message. So I have in total a maximum of 4 chunks of images by 9 items each in variable dl.imgs (It may be only 1 chunk with only 1 image).

What I need is to send first two chunks (18 images) with 5 sec delay, then third after 60 sec delay and last one with 5 sec delay. So I can avoid hitting that error. I wrote a code above, which should do that, but I think I wrongly understood how setTimeout works in this scope.

Bohdan
  • 53
  • 5

1 Answers1

0

I have implemented the following for retrial in case I encounter a 429 error. However, it does not really avoid it. I assume the bot.sendMediaGroup() should make itself sure that it does not exceed the max requests per second/minute, which it obviously doesn't. Instead one may workaround the issue by sending each item separately (not in a media group) and making sure to wait properly before sending the the next item.

try {
  const msg = await bot.sendMediaGroup(chatId, media, options);
  msg.forEach( m => messages.push(m));
  await delay(60000); // sleep 1 minute so not to exceed the rate limit
} catch (error) {
  if (error.response && error.response.statusCode === 429) {
    const retryAfterSeconds = error.response.headers['retry-after'] + 10 || 60;
    console.warn(`Too many requests, waiting for ${retryAfterSeconds} seconds before retrying...`);
    await new Promise(resolve => setTimeout(resolve, retryAfterSeconds * 1000));
    console.log('Retrying...');
    i--; // Retry the same iteration
  } else {
    console.error('Failed to send media group:', error);
  }
}