node.jstelegramtelegram-botnode-telegram-bot-api

Node telegram bot api - disable processing of updates sent before the bot starts


I, have this issue: when I start the bot it immediately starts looking for updates. However, in my particular case (especially during the developing) this can be very frustrating and uncomfortable. There is a way to tell the bot to process the update sent after the starting of the bot itself?

Thank you


Solution

  • You need to tell Telegram to "forget" those updates. This is how you would do it:

    1. Send a request to: https://api.telegram.org/bot$TELEGRAM_TOKEN/getUpdates
    2. Get the message_id of the last element (pop) of the result array
    3. Send another request https://api.telegram.org/bot$TELEGRAM_TOKEN/getUpdates?offset=$OFFSET where $OFFSET is the message_id + 1

    This is a stateless way of clearing pending requests. You can use curl,the browser or a request library (recommended) to do this. You can do this with node-telegram-bot-api but I don't recommend since you will have to create 2 bot instances, 1 polling and 1 non polling to clear the updates which is not a good practice since ntba doesn't decouple its methods in a different class.

    So in pseudocode code:

    const TOKEN = 'MY_TOKEN'
    
    async function clearUpdates(token) {
      const { result } = await request.get(`https://api.telegram.org/bot${token}/getUpdates`).json()
      
      return await request.get(`https://api.telegram.org/bot${token}/getUpdates?offset=${result[result.length - 1].message_id + 1}`)
    }
    

    Now run clearUpdates before starting your bot.