Search code examples
javascriptgoogle-sheetsdiscorddiscord.jsgoogle-sheets-api

How can i read and write to cells in the same function?


I would like to read the spreadsheet cell H2 in the same function blackList

With this script, i am currently writing to cell H1. I would like to read cell H2 as well.

This is my updated script:

const { setTimeout } = require("timers/promises"); // cause a delay if needed

async function blackList() { 
    const sheets = google.sheets({ version: "v4", auth });
    const spreadsheetId = "myidhere";
  
    const sheetName = "BOTDATA";
    const cells = ["H1"];
    const valueInputOption = "USER_ENTERED";
    const userInput = interaction.options.get('steamid').value;
    await sheets.spreadsheets.values.update({
      spreadsheetId,
      range: `'${sheetName}'!${cells[0]}`,
      resource: { values: [[userInput]] },
      valueInputOption,
    });
     await setTimeout(1000); // set time on delay if needed

    const obj = await sheets.spreadsheets.values.get({spreadsheetId, range: `'${sheetName}'!H2`});
    const value = obj.data.values[0][0];
   // console.log(value);
    return value;
  }

})()

Solution

  • I believe your goal is as follows.

    • You want to put a value to a cell "H1" and want to retrieve a value from "H2". From Depending on the value of the cell 'H1' is when the userInput is updated, it will change cell "H2" Value. And i would like to display H2., it seems that the value "H2" is changed by the value of "H1".

    In this case, how about the following modification?

    Modified script:

    const { setTimeout } = require("timers/promises"); // added
    
    async function blackList() {
      const sheets = google.sheets({ version: "v4", auth });
      const spreadsheetId = "myIdhere";
    
      const sheetName = "BOTDATA";
      const cells = ["H1"];
      const valueInputOption = "USER_ENTERED";
      const userInput = interaction.options.get("steamid").value;
      await sheets.spreadsheets.values.update({
        spreadsheetId,
        range: `'${sheetName}'!${cells[0]}`,
        resource: { values: [[userInput]] },
        valueInputOption,
      });
    
      await setTimeout(2000); // Please adjust this value to your situation.
    
      const obj = await sheets.spreadsheets.values.get({spreadsheetId, range: `'${sheetName}'!H2`});
      const value = obj.data.values[0][0];
      console.log(value);
    }
    
    • In this modification, after a value was put into the cell "H1", the cell value of "H2" is retrieved.
    • In this modification, the wait time is set for calculating the formula of "H2". But, I have no information about your actual situation. So, I'm not sure whether await setTimeout(2000); is required to be used. So, please test with and without it, and decide whether you use it.

    Note:

    • setTimeout can be used after Node.js 16. Please be careful about this.