Integrating Telegram Bot with Google Sheets

Hello everyone! This is my first time posting in this community and I’m seeking assistance with creating a Telegram bot that captures messages from my Telegram channel and logs the details into a Google Sheet. I’m utilizing Apps Script for this task, and I’ve inserted the following script for your review. The webhook seems to be functioning correctly, as my test deployments are successful, but when I send a message via Telegram, there is no response from the bot. Instead, I receive an error message stating: “last_error_message”: “Wrong response from the webhook: 302 Moved Temporarily”. Below, I’ve included my code (excluding the bot token and web app link). Please share any insights you may have on resolving this issue, as I’ve been troubleshooting for several days now and am feeling quite stuck.

/**
 * Telegram Bot Connection with Google Sheets
 */

const SHEET_NAME = '...'; // Specify the target Google Sheet

function configureTelegramToken() {
  const ui = SpreadsheetApp.getUi();
  const result = ui.prompt('Specify Telegram Token', 'Enter your Telegram bot token:', ui.ButtonSet.OK_CANCEL);

  if (result.getSelectedButton() == ui.Button.OK) {
    const token = result.getResponseText().trim();
    if (token) {
      PropertiesService.getScriptProperties().setProperty('TELEGRAM_TOKEN', token);
      ui.alert('Success', 'Telegram token configured successfully.', ui.ButtonSet.OK);
    } else {
      ui.alert('Error', 'Token cannot be empty. Please retry.', ui.ButtonSet.OK);
    }
  }
}

function getTelegramToken() {
  const token = PropertiesService.getScriptProperties().getProperty('TELEGRAM_TOKEN');
  if (!token) {
    throw new Error('Telegram token is unset. Run configureTelegramToken() initially.');
  }
  return token;
}

function handleGetRequest(e) {
  return HtmlService.createHtmlOutput('Webhook is operational. Awaiting Telegram updates.');
}

function handlePostRequest(e) {
  try {
    Logger.log('handlePostRequest initiated.');

    if (!e || !e.postData || !e.postData.contents) {
      return ContentService.createTextOutput(JSON.stringify({ status: 'error', message: 'No POST data available.' }))
                           .setMimeType(ContentService.MimeType.JSON);
    }
    // ... (remaining parsing and logging code here)
  } catch (error) {
    Logger.log('Error in handlePostRequest: ' + error.message);
    return ContentService.createTextOutput(JSON.stringify({ status: 'error', message: error.message }))
                         .setMimeType(ContentService.MimeType.JSON);
  }
}

function sendTelegramResponse(chatId, message) {
  const TELEGRAM_TOKEN = getTelegramToken();
  const apiUrl = `https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage`;
  const requestData = { chat_id: chatId, text: message };
  const config = { method: 'post', contentType: 'application/json', payload: JSON.stringify(requestData) };

  try {
    const apiResponse = UrlFetchApp.fetch(apiUrl, config);
    Logger.log('Response from sendTelegramResponse: ' + apiResponse.getContentText());
  } catch (error) {
    Logger.log('Error while sending response: ' + error.message);
  }
}

function initiateWebhook() {
  const TELEGRAM_TOKEN = getTelegramToken();
  const webAppUrl = 'https://script.google.com/macros/s/.../exec';
  const url = `https://api.telegram.org/bot${TELEGRAM_TOKEN}/setWebhook?url=${encodeURIComponent(webAppUrl)}`;
  try {
    const response = UrlFetchApp.fetch(url);
    Logger.log('Webhook setup complete: ' + response.getContentText());
  } catch (error) {
    Logger.log('Error setting up webhook: ' + error.message);
  }
}

I’m eager to hear any advice that might help, as I’m feeling quite lost with the coding aspects.

From my experience, that ‘302 Moved Temporarily’ error could be due to the web app URL not being publicly accessible or the script being set to the wrong deployment mode. Double-check if your Google Apps Script is deployed as a web app with “Anyone, even anonymous” access. Another potential issue could be the URL redirection behavior; make sure your web app URL doesn’t redirect elsewhere. Additionally, ensure that the URL you use for setting the webhook is correct and matches the deployment version. Since Google Scripts recently changed some deployment settings, a mismatch here could result in webhooks not being recognized properly.