witnessmenow / Universal-Arduino-Telegram-Bot

Use Telegram on your Arduino (ESP8266 or Wifi-101 boards)
MIT License
1.09k stars 302 forks source link

Overflow array in bot.messages when numNewMessages >1 #274

Open joroMaser opened 2 years ago

joroMaser commented 2 years ago

In UniversalTelegramBot.h we can see:

#define HANDLE_MESSAGES 1
telegramMessage messages[HANDLE_MESSAGES];

So in examples that you show how to handle message

void handleNewMessages(int numNewMessages)
{
  for (int i = 0; i < numNewMessages; i++)
  {
    bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].text, "");
  }
}

If numNewMessages will be bigger than 1 the program will crash , because the maximum size of bot.messages is 1

palmerabollo commented 2 years ago

No, it won't crash @joroMaser.

The bot.getUpdate code always return one update at a time. That is, the array length will always be 1. The question "why are we using an array?" was also raised at https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/issues/65

This is why you see code along these lines:

    int num_messages = bot.getUpdates(bot.last_message_received + 1); // 0..1

    while (num_messages) {
        handle_new_messages(bot.messages)
        num_messages = bot.getUpdates(bot.last_message_received + 1); // <- extra polling
    }

When something like this should be enough, in my opinion:

    int num_messages = bot.getUpdates(bot.last_message_received + 1); // 0..N

    for (int i = 0; i < num_messages; i++) {
        handle_new_message(bot.messages[i]);
    }

I guess HANDLE_MESSAGES should be configurable in the future, to be able to process several messages in a single batch.