Сценарий Google Apps: ошибка «Функция сценария не найдена» - PullRequest
0 голосов
/ 01 октября 2018

Я искал решение для своей проблемы, но не смог найти его, и в результате пишу свой первый вопрос в Переполнение стека.

В настоящее время я пишу простую программу на Google Apps Script, которая отправляет пользователю напоминание по электронной почте, если он забывает отправить форму Google к определенной дате.Прямо сейчас у меня есть 3 различные функции: onFormSubmit, scheduleTrigger и reminderEmail.Ниже приведен код, который я написал до сих пор:

/**
This function searches the Google Form for the date when the previous
session was held & the date when the next session will be held. 
This function also calculates the date when to remind the user if they
forget to submit the Google Form. This reminder date is calculated to be 2 
days after the date when the next session is held. 
This function calls the next function: scheduleTrigger.
*/
function onFormSubmit(e) {
    var form = FormApp.getActiveForm();
    var frm = FormApp.getActiveForm().getItems();
    var futureDate = new Date(e.response.getResponseForItem(frm[3]).getResponse());
    var pastDate = new Date(e.response.getResponseForItem(frm[0]).getResponse());

    var reminderDate = new Date(futureDate.setDate(futureDate.getDate() + 2));
    futureDate.setDate(futureDate.getDate() - 2);

    scheduleTrigger(reminderDate, futureDate, pastDate, form);
}

/**
This function schedules the reminder email trigger at a specific date. The
specific date is the reminder date that was calculated in the previous function.    
This function calls the next function: reminderEmail. 
*/
function scheduleTrigger(reminderDate, futureDate, pastDate, form) {
    ScriptApp.newTrigger('reminderEmail(reminderDate, futureDate, pastDate, form)').timeBased().atDate(reminderDate.getFullYear(), reminderDate.getMonth(), reminderDate.getDate()).inTimezone('America/New_York').create();
}

/**
This function checks the submissions if the form has been submitted. 
If there is no submission, then it sends out an email reminder. 
*/
function reminderEmail(reminderDate, futureDate, pastDate, form) {
    var count = 0;
    var formResponses = form.getResponses();
    for (var i = 0; i < formResponses.length; i++) {
        var formResponse = formResponses[i];
        var itemResponses = formResponse.getItemResponses();
        for (var j = 0; j < itemResponses.length; j++) {
            var itemResponse = itemResponses[j];
            if (itemResponse == futureDate) {
                count++; 
            }
        }
    }

    if (count != 2) {
        MailApp.sendEmail("test@gmail.com",
                          "Submit Form Reminder",
                          "Hey! You didn't fill out the form yet!");
    };
}

Проблема, с которой я сталкиваюсь, заключается в том, что я получаю сообщение об ошибке, в котором говорится, что «выбранная функция не найдена» для функции replyderEmail при каждом запуске программы,Я посмотрел вокруг и следил за предыдущими сообщениями, сделанными для решения этой проблемы, такими как переименование функции и перезапуск с совершенно новым Google From, но ничего не помогло.У меня также есть полное владение и авторизация для скрипта, поэтому разрешения не должны быть проблемой.

Пожалуйста, дайте мне знать, если у вас есть идеи о том, как решить эту проблему.Любые отзывы приветствуются!Если есть какая-то часть моего вопроса, которая неясна, пожалуйста, дайте мне знать.Спасибо, что нашли время, чтобы прочитать этот длинный пост.

1 Ответ

0 голосов
/ 01 октября 2018

Причиной сбоя является то, что вам нужно только передать имя функции в ScriptApp.newTrigger.Вы не можете отправить параметры с ним, это то, что вам придется обрабатывать другими способами.

Документация

/**
This function searches the Google Form for the date when the previous session was held & the date when the next session will be held. 
This function also calculates the date when to remind the user if they forget to submit the Google Form. This reminder date is calculated to be 2 days after the date when the next session is held. 
This function calls the next function: scheduleTrigger.
*/
function onFormSubmit(e) {
  var form = FormApp.getActiveForm();
  var frm = FormApp.getActiveForm().getItems();
  var futureDate = new 
Date(e.response.getResponseForItem(frm[3]).getResponse());
  var pastDate = new 
Date(e.response.getResponseForItem(frm[0]).getResponse());

  var reminderDate = new Date(futureDate.setDate(futureDate.getDate() + 2));
  futureDate.setDate(futureDate.getDate() - 2);

  scheduleTrigger(reminderDate);
}

/**
This function schedules the reminder email trigger at a specific date. The specific date is the reminder date that was calculated in the previous function.    
This function calls the next function: reminderEmail. 
*/
function scheduleTrigger(reminderDate) {
  ScriptApp.newTrigger('reminderEmail').timeBased().atDate(reminderDate.getFullYear(), reminderDate.getMonth(), reminderDate.getDate()).inTimezone('America/New_York').create();
}

/**
This function checks the submissions if the form has been submitted. If there is no submission, then it sends out an email reminder. 
*/
function reminderEmail() {
  var form = FormApp.getActiveForm();
  var count = 0;
  var formResponses = form.getResponses();
  for (var i = 0; i < formResponses.length; i++) {
   var formResponse = formResponses[i];
   var itemResponses = formResponse.getItemResponses();
    for (var j = 0; j < itemResponses.length; j++) {
      var itemResponse = itemResponses[j];
      if (itemResponse == futureDate) { // Unsure what this part is for, perhaps you should find another way to calculate this.
        count++; 
      }
    }
  }

  if (count != 2) {
    MailApp.sendEmail("test@gmail.com",
                      "Submit Form Reminder",
                      "Hey! You didn't fill out the form yet!");
  };
}

Я смог очистить вашкод, чтобы он работал, но не уверен насчет futureDate в функции reminderEmail.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...