3

I have created a google sheet with a lot of info for a beach volleyball cup and I want to call an API I have created when a checkbox is checked in this sheet.

function onEdit(e){
  const ui = SpreadsheetApp.getUi();
  const spreadsheets = SpreadsheetApp.getActive();
  const configSheet = spreadsheets.getSheetByName("Config")
  var tourneyId = String(configSheet.getRange(2,4).getValue())
  var tourneyTitle = String(configSheet.getRange(2,5).getValue())
  var sheet = spreadsheets.getActiveSheet()
  if (sheet.getName() == "LiveScore"){
    var actRng = sheet.getActiveRange();
    var editColumn = actRng.getColumn();
    var rowIndex = actRng.getRowIndex();
    actRng = actRng.getCell(1, 1);
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
    if(editColumn == 7 && rowIndex != 1){
      onStartBroadcastClicked(actRng, ui, sheet, rowIndex, editColumn, tourneyTitle);
    }
  }
}

There is never any problems with this part as I see it. But when i get into the function onStartBroadcastClicked:

function onStartBroadcastClicked(actRng, ui, sheet, rowIndex, editColumn, tourneyTitle){
  var homeTeam = String(sheet.getRange(rowIndex, 14).getValue());
... // more setting variables
  var endTime = new Date(startTime.getTime() + MILLIS_PER_MATCH);

  if(actRng.isChecked()){
    var response = ui.alert("You are about to start a new broadcast. Are you sure?" +
                            "\n Title: " + title, ui.ButtonSet.YES_NO);
    if (response == ui.Button.YES) {
      var httpRequest = "https://someUrl";
      var options =
          {
            'method':'POST',
            'contentType': 'application/json',
            'payload' : JSON.stringify({
              "title" : title,
                  ... // setting all variables
              "description" : description
            }),
            'muteHttpExceptions' : true,
            'headers' : {
              "Authorization": "Basic " + Utilities.base64Encode(USERNAME + ":" + PASSWORD)
            }
          };

      ui.alert("Waiting.......")
      var result = UrlFetchApp.fetch(httpRequest, options);
      ui.alert(result.getContentText())

The issue is that it always gets to the line ui.alert("Waiting......."), but when triggered from the checkbox, it never succeeds the http POST request. If I click play inside the editor, it succeeds and I got the response in the alertbox.

Could it be some timeout or some autosave issues? Does anyone have any idea if where to keep looking? I've been stuck here for some time now and I would be really happy if anyone can point me to the correct direction.

3
  • 2
    When the methods which are required to authorize used at the simple trigger, the error occurs. So in this case, how about using the installable triggers of OnEdit event trigger? developers.google.com/apps-script/guides/triggers/installable At that time, please rename onEdit() to other function name, and install the renamed function name as the OnEdit event trigger. By this, the duplicate run of onEdit() can be prevented. By these settings, when the cell is edited, UrlFetchApp.fetch() works. If this was not the direct solution of your issue, I apologize.
    – Tanaike
    Commented May 10, 2019 at 8:45
  • 1
    It is correct that we need to authorize so it can call outside sources. If you want to add your comment as your answer I will mark it correct Commented May 10, 2019 at 21:03
  • Thank you for replying. I'm glad your issue was resolved. I posted it including some information as an answer. Could you please confirm it?
    – Tanaike
    Commented May 10, 2019 at 23:13

2 Answers 2

2

The modification point of your issue is to use the installable trigger of OnEdit event. When the methods which are required to authorize used at the simple trigger, the error occurs. This situation makes us think that it seems the script doesn't work.

In order to avoid this error, please use the installable triggers of OnEdit event trigger.

As an important point, before you install the trigger, please rename the function name of onEdit() to other name. And install the renamed function name as the OnEdit event trigger. By this, the duplicate run of onEdit() can be prevented. If onEdit() function is installed as the installable trigger, when a cell is edited, the function is run 2 times. Ref.

By above settings, when the cell is edited, UrlFetchApp.fetch() works.

References:

1
  • 1
    Thank you so much! You saved my day! Commented May 12, 2019 at 19:25
0

I was able to get a script to work with a trigger if I created the script from script.google.com and call the Google Sheet and tab from the script. I'm manually entered in my API calls per cell within a specified Row:

function fetchUrls() {
    var spreadsheetId = "ENTER GOOGLE SHEET ID";
    var spreadsheet = SpreadsheetApp.openById(spreadsheetId);
    var sheet = spreadsheet.getSheetByName("ENTER SHEET NAME");
    var range = sheet.getRange("ENTER RANGE OR FULL COLUMN"); // specify the range of cells in column B
    var urls = range.getValues(); // get the values of the cells and store them 
    in an array
    
    var cache = CacheService.getScriptCache();
    
    for (var i = 0; i < urls.length; i++) {
        if(urls[i][0] != "") { // check if the current cell is not empty
            var url = urls[i][0];
            var result = cache.get(url);
            if(!result) {
                var response = UrlFetchApp.fetch(url);
                result = response.getContentText();
                cache.put(url, result, 21600);
            }
            sheet.getRange(i+1,3).setValue(result); // set the value of the current cell to the result of the API call in column C
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.