I am trying to send multiple messages to telegram bot through telegraf API in node backend. There are various conditions which when true, should send an telegram alert. The example of condition is:
if(condition is true) {
message = "Hey there";
sendToTGBot(message)
}
There are approximately 100 conditions which get checked within few seconds when the data is fetched as a stream from the API. So, the telegram bot limit gets hit when trying to process more than 30 messages in a second and the server crashes.
The code used to send messages from the bot is:
export const sendToTGBot = (alert) => {
bot.telegram.sendMessage(chat_id, alert);
}
I have also tried putting a delay using setTimeout() in the above code as:
export const sendToTGBot = (alert) => {
setTimeout(() => {
bot.telegram.sendMessage(chat_id, alert);
}, 500);
}
This code above puts the delay (I think so), but due to approximately 30-50 conditions getting true at once in a second. The function gets called that many times and after approx. 10-15 seconds all the alerts get sent simultaneously, again hitting the telegram bot limit.
Also, tried it like this:
export const sendToTGBot =
setTimeout((alert) => {
bot.telegram.sendMessage(chat_id, alert);
}, 500);
This results in a straight error.
Kindly help me with this problem. I have to send multiple alerts within a duration. The number of alerts simultaneously can increase. So, recommend me the best possible solution using JavaScript. Thanks.
You can do this by adding the messages in a queue/array, then utilize async await to loop it
let queue = [];
if(condition == true) {
message = "Hey there";
queue.push(message);
}
setInterval(async ()=>{
if(queue.length>0) {
await bot.telegram.sendMessage(chat_id, queue[0]);
queue.shift();
}
}, 1000)