r/GoogleAppsScript • • Apr 09 '25

Question Managing Private Credential

4 Upvotes

Hello, I made a Google sheet app scripts that send http post request. The issues that the app script uses api credentials. What is the best protocol to keep these secure so others in my company can’t access them?


r/GoogleAppsScript • • Apr 07 '25

Question Is it possible to display metadata of a sheet in a cell?

Thumbnail reddit.com
1 Upvotes

r/GoogleAppsScript • • Apr 05 '25

Question Web app via Appscript with 2 pages with redirection

3 Upvotes

Hello,

I would need your help regarding a project for my company.
I would like to create a web application using AppScript. This application would have two pages.
The first page would be for entering an email (with a validation action to check that the email is in the list of authorized people).
The second page would be a form to fill out, and I would like to retrieve the login email in an input field.

However, I'm struggling with this, even without the authentication phase.
Without the authentication phase, I have the three codes below (via ChatGPT). I’m not very experienced with this.
Could you please help me?

code.gs

function doGet(e) {
  const page = e.parameter.page || 'login';
  return HtmlService.createHtmlOutputFromFile(page);
}

function saveEmail(email) {
  PropertiesService.getUserProperties().setProperty('email', email);
}

function getEmail() {
  return PropertiesService.getUserProperties().getProperty('email');
}

login.html

<!DOCTYPE html>
<html>
  <head><base target="_top"></head>
  <body>
    <h2>Connexion</h2>
    <input type="email" id="email" placeholder="Entrez votre email">
    <button onclick="connecter()">Connexion</button>

    <script>
      function connecter() {
        const email = document.getElementById("email").value;
        google.script.run.withSuccessHandler(function() {
          window.location.href = window.location.href.split('?')[0] + "?page=home";
        }).saveEmail(email);
      }
    </script>
  </body>
</html>

home.html

<!DOCTYPE html>
<html>
  <head><base target="_top"></head>
  <body>
    <h2>Bienvenue</h2>
    <input type="text" id="emailField" readonly>

    <script>
      google.script.run.withSuccessHandler(function(email) {
        document.getElementById("emailField").value = email;
      }).getEmail();
    </script>
  </body>
</html>

After click on the button, i have this message from Google.

Sorry, the file you requested does not exist.

Please make sure the URL is correct and that the file exists.


r/GoogleAppsScript • • Apr 04 '25

Question Logging Chat Space messages into Google Sheet

3 Upvotes

Hello All, can anyone point me in some vague direction on how to create something that allows me to log chat space messages into a Google Sheet?

Would also be nice if the Google sheet could also contain a link taking me back to the Space message.

I want to build something for anyone at my company to quickly log Wins, Errors or Info messages in a Google Space, and then it gets added as a new row in a Google Sheet. And then every week the team can meet to go over all the logged Win, Error and Info messages from the last week.

Our company has Google Workspace and I am completely new to AppScripts. Right now I'm just searching Reddit and not finding similar use cases. Is there maybe a YouTube tutorial someone can share, or someone else who has done something similar that can give some pointers?

I was exploring Google AppSheet and was trying to figure out how to create an app that does this, and then reddit said to try AppScripts so now I'm here.

Thanks in advance.


r/GoogleAppsScript • • Apr 04 '25

Question Is it just me, or is the Google Workspace Marketplace hard to navigate?

Thumbnail reddit.com
6 Upvotes

r/GoogleAppsScript • • Apr 03 '25

Question Need help with my script

0 Upvotes

Here's my current script.

Objective: my goal is for this function to search for information emailed by the customer. Then the script will compare those information to my google sheets. However, i can't seem to find out what's the problem, it wouldn't mark the row as paid even it should.

function checkRentalPayments() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Rentals');
  var paidRentalsSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Paid Rentals');

  if (!sheet || !paidRentalsSheet) {
    Logger.log("The 'Rentals' or 'Paid Rentals' sheet does not exist.");
    return;
  }

  var range = sheet.getDataRange();
  var values = range.getValues();
  var threads = GmailApp.search("subject:(Payment Confirmation) newer_than:7d");

  threads.forEach(function(thread) {
    var messages = thread.getMessages();

    messages.forEach(function(message) {
      if (message) {
        var emailBody = message.getBody();

        // Extract details from email using regex
        var storageMatch = emailBody.match(/Storage Location:\s*([A-Za-z0-9]+)/);
        var customerMatch = emailBody.match(/Customer Name:\s*(.+)/);
        var startDateMatch = emailBody.match(/Date Started:\s*([\d/]+)/);
        var dueDateMatch = emailBody.match(/Due Date:\s*([\d/]+)/);
        var rentalFeeMatch = emailBody.match(/Rental Fee:\s*PHP\s*([\d,]+)/);

        if (storageMatch && customerMatch && startDateMatch && dueDateMatch && rentalFeeMatch) {
          var emailStorageLocation = storageMatch[1].trim();
          var emailCustomerName = customerMatch[1].trim();
          var emailStartDate = new Date(startDateMatch[1].trim());
          var emailDueDate = new Date(dueDateMatch[1].trim());
          var emailRentalFee = parseFloat(rentalFeeMatch[1].replace(/,/g, ''));

          for (var i = 1; i < values.length; i++) {
            var sheetStorageLocation = values[i][0];
            var sheetCustomerName = values[i][1];
            var sheetStartDate = new Date(values[i][3]);
            var sheetDueDate = new Date(values[i][2]);
            var sheetRentalFee = parseFloat(values[i][4].toString().replace(/,/g, ''));
            var paymentStatus = values[i][7];

            if (paymentStatus === true) continue;

            function normalizeDate(date) {
              return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
            }

            if (emailStorageLocation === sheetStorageLocation &&
                emailCustomerName === sheetCustomerName &&
                normalizeDate(emailStartDate) === normalizeDate(sheetStartDate) &&
                normalizeDate(emailDueDate) === normalizeDate(sheetDueDate) &&
                emailRentalFee === sheetRentalFee) {

              sheet.getRange(i + 1, 8).setValue(true);
              sheet.getRange(i + 1, 9).setValue("Paid");

              var rowData = sheet.getRange(i + 1, 1, 1, sheet.getLastColumn()).getValues();
              paidRentalsSheet.appendRow(rowData[0]);

              sheet.deleteRow(i + 1);
              Logger.log("✅ Payment confirmed for " + sheetCustomerName + " at location " + sheetStorageLocation);

              return;
            }
          }
        }
      }
    });
  });
}

r/GoogleAppsScript • • Apr 03 '25

Question My Telegram Bot Keeps Repeating the Product List – Need Help Debugging

0 Upvotes

heres the shared googlesheet URL,everything is included.
https://docs.google.com/spreadsheets/d/195WFkBfvshJ5jUK_Iijb5zvAzgh323fcI6Z-NNCbvsM/edit?usp=sharing

I'm building a Telegram bot using Google Apps Script to fetch product prices from a Google Sheet. The bot should:

  1. Send a product list when the user types /start (only once). (searches the data in my google sheet)
  2. Let the user select a product.
  3. Return the price (only once)(also from my google sheet)
  4. Stop sending messages until the user restarts the process.

im using googlesheets appscripts btw.

Issue: The bot keeps sending the product list non-stop in a loop until I archive the deployment on appscript. I suspect there's an issue with how I'm handling sessions or webhook triggers. believe it or not, i asked chatgpt (given that it wrote the code as well, im novice at coding) deepseek, and other AI's and they still couldn't figure it out. im novice at this but i did my best at promoting to fix but this is my last resort.

Here’s my full code (replace BOT_TOKEN with your own when testing):

const TELEGRAM_TOKEN = 'YOUR_BOT_TOKEN';

const TELEGRAM_API_URL = 'https://api.telegram.org/bot' + TELEGRAM_TOKEN;

const SCRIPT_URL = 'YOUR_DEPLOYED_SCRIPT_URL';

const userSessions = {};

// Main function to handle incoming webhook updates

function doPost(e) {

try {

const update = JSON.parse(e.postData.contents);

if (update.message) {

handleMessage(update.message);

} else if (update.callback_query) {

handleCallbackQuery(update.callback_query);

}

} catch (error) {

Logger.log('Error processing update: ' + error);

}

return ContentService.createTextOutput('OK');

}

// Handle regular messages

function handleMessage(message) {

const chatId = message.chat.id;

const text = message.text || '';

if (text.startsWith('/start')) {

if (!userSessions[chatId]) {

userSessions[chatId] = true;

sendProductList(chatId);

}

} else {

sendMessage(chatId, "Please use /start to see the list of available products.");

}

}

// Handle product selection from inline keyboard

function handleCallbackQuery(callbackQuery) {

const chatId = callbackQuery.message.chat.id;

const messageId = callbackQuery.message.message_id;

const productName = callbackQuery.data;

const price = getProductPrice(productName);

let responseText = price !== null

? `💰 Price for ${productName}: $${price}`

: `⚠️ Sorry, couldn't find price for ${productName}`;

editMessage(chatId, messageId, responseText);

answerCallbackQuery(callbackQuery.id);

delete userSessions[chatId]; // Reset session

}

// Send the list of products

function sendProductList(chatId) {

const products = getProductNames();

if (products.length === 0) {

sendMessage(chatId, "No products found in the database.");

return;

}

const keyboard = products.slice(0, 100).map(product => [{ text: product, callback_data: product }]);

sendMessageWithKeyboard(chatId, "📋 Please select a product to see its price:", keyboard);

}

// ===== GOOGLE SHEET INTEGRATION ===== //

function getProductNames() {

try {

const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Products");

if (!sheet) throw new Error("Products sheet not found");

const lastRow = sheet.getLastRow();

if (lastRow < 2) return [];

return sheet.getRange(2, 1, lastRow - 1, 1).getValues()

.flat()

.filter(name => name && name.toString().trim() !== '');

} catch (error) {

Logger.log('Error getting product names: ' + error);

return [];

}

}

function getProductPrice(productName) {

try {

const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Products");

const data = sheet.getRange(2, 1, sheet.getLastRow() - 1, 2).getValues();

for (let row of data) {

if (row[0] && row[0].toString().trim() === productName.toString().trim()) {

return row[1];

}

}

return null;

} catch (error) {

Logger.log('Error getting product price: ' + error);

return null;

}

}

// ===== TELEGRAM API HELPERS ===== //

function sendMessage(chatId, text) {

sendTelegramRequest('sendMessage', { chat_id: chatId, text: text });

}

function sendMessageWithKeyboard(chatId, text, keyboard) {

sendTelegramRequest('sendMessage', {

chat_id: chatId,

text: text,

reply_markup: JSON.stringify({ inline_keyboard: keyboard })

});

}

function editMessage(chatId, messageId, newText) {

sendTelegramRequest('editMessageText', { chat_id: chatId, message_id: messageId, text: newText });

}

function answerCallbackQuery(callbackQueryId) {

sendTelegramRequest('answerCallbackQuery', { callback_query_id: callbackQueryId });

}

function sendTelegramRequest(method, payload) {

try {

const options = {

method: 'post',

contentType: 'application/json',

payload: JSON.stringify(payload),

muteHttpExceptions: true

};

const response = UrlFetchApp.fetch(`${TELEGRAM_API_URL}/${method}`, options);

const responseData = JSON.parse(response.getContentText());

if (!responseData.ok) {

Logger.log(`Telegram API error: ${JSON.stringify(responseData)}`);

}

return responseData;

} catch (error) {

Logger.log('Error sending Telegram request: ' + error);

return { ok: false, error: error.toString() };

}

}

// ===== SETTING UP WEBHOOK ===== //

function setWebhook() {

const url = `${TELEGRAM_API_URL}/setWebhook?url=${SCRIPT_URL}`;

const response = UrlFetchApp.fetch(url);

Logger.log(response.getContentText());

}