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.

    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);
    }
    

    Note: