Previous message cannot deleted using node-telegram-bot-api [Telegram Bot]

When user click previous or next button, bot not delete the previous message before it send new page

More Detail

My expectation is my bot should delete the previous message when user click previous or next button, but my bot not delete the previous message and directly send new page content

Here is my code:

async function sendResultsPage(chatId, page, query, previousMessageId) {
  const results = resultCache[chatId];
  const startIdx = (page - 1) * resultsPerPage;
  const endIdx = Math.min(startIdx + resultsPerPage, results.length);
  const totalPages = Math.ceil(results.length / resultsPerPage);

  const pageResults = results.slice(startIdx, endIdx);

  // Create an inline keyboard for navigation and product names
  const keyboard = [
    // Add product names as buttons
    ...pageResults.map((product) => [
      {
        text: product.title,
        callback_data: `view_${product.link}`, // Include the product link in callback_data
      },
    ]),
    [
      {
        text: 'Previous',
        callback_data: 'prev',
      },
      {
        text: `${page}/${totalPages}`,
        callback_data: 'page',
      },
      {
        text: 'Next',
        callback_data: 'next',
      },
    ],
  ];

  const options = {
    reply_markup: {
      inline_keyboard: keyboard,
    },
  };

  // Create a message indicating the result for the query
  const message = `This is the result for "${query}"`;

  // Delete the previous message if the previousMessageId is provided
  if (previousMessageId) {
    try {
      await bot.deleteMessage(chatId, previousMessageId);
    } catch (error) {
      console.error('Error deleting previous message:', error);
    }
  }

  // Send the new message and return the message ID for future deletions
  const sentMessage = await bot.sendMessage(chatId, message, options);
  return sentMessage.message_id;
}

Leave a Comment