Сбой скрипта из-за indexOf только при запуске (не при тестировании) - PullRequest
3 голосов
/ 08 января 2020

Я играю со скриптом Google Apps и злюсь.

Следующий код работает отлично, как при нажатии кнопок «Выполнить», так и при отладке на сайте скрипта Google Apps. Но, пытаясь выполнить его с помощью тириггера, я всегда получаю странную ошибку:

TypeError: Fonction indexOf introuvable dans l'objet {year = 2020, month = 1, день месяца = 8, день недели = 3, неделя года = 2, час = 17, минута = 57, секунда = 56, часовой пояс = UT C, authMode = FULL, triggerUid = 2998093}. at createIssueReminder (Код: 39)

Это по-французски, но говорит function indexOf not found in object {year=2020, month=1, day-of-month=8, day-of-week=3, week-of-year=2, hour=17, minute=57, second=56, timezone=UTC, authMode=FULL, triggerUid=2998093}

Вот странная часть: хотя сообщение согласуется с самим собой (ну, объект не является массив, поэтому он не может использовать indexOf), это совершенно не согласуется с моим кодом, так как categories является массивом, и indexOf вызывается для него. И где, черт возьми, я пытаюсь вызвать indexOf из экземпляра даты!?

Как уже говорилось, этот кусок кода отлично работает из редактора скриптов Google Apps, я не могу понять, почему и где он сбой при выполнении триггером ...

Любое понимание этого будет высоко оценено. Спасибо всем. Ты моя единственная надежда, Оби-Ван Кеноби.

/**
 * Check each week if we need a reminder for the week's issue, provided the issue matches the user's chosen categories.
 * @param {string[]} categories The watched categories.
 */
function createIssueReminder(categories) {
  if (!categories)
  {
    categories = ["S", "DD", "D", "M"];
  }
  // Get the "Censored SS Title" spreadsheet
  // cf https://docs.google.com/spreadsheets/d/ss-id-here/
  var spreadsheet = SpreadsheetApp.openById("ss-id-here");

  // Get the sheet storing the issues
  var issueSheet = spreadsheet.getSheetByName("Sorties");

  // Get the range storing the data
  var issueRange = issueSheet.getRange("A2:D81");

  // Get the data from the range
  // use data[row][column] to access values
  var issueData = issueRange.getValues();

  // Get current date and formatted date, in French format Utilities.formatDate(new Date(), "CET", "dd/MM/yy")
  var currentDate = new Date();

  var rowIndex = 0;

  for (rowIndex; rowIndex < issueData.length; rowIndex++)
  { // repeat loop until end of data
    var rowDate = issueData[rowIndex][0];

    // if the date in the cell is today's date...
    if (rowDate.getDate() == currentDate.getDate() && 
        rowDate.getMonth() == currentDate.getMonth() && 
        rowDate.getFullYear() == currentDate.getFullYear())
    { 
      // if the issue's category matches any category set for the user...
      if (categories.indexOf(issueData[rowIndex][3]) != -1)
      {
          // add a reminder with the issue number and content
          createIssueReminderEvent(issueData[rowIndex][3], issueData[rowIndex][1], issueData[rowIndex][2]);
      }
    }
  }  
}

/**
 * Add a reminder to the calendar.
 * @param {number} issueNumber The number of the issue.
 * @param {string} issueMessage The content of the issue.
 */
function createIssueReminderEvent(category, issueNumber, issueMessage) {
  // Prepare the message
  var title = "Issue #"+issueNumber+" ["+category+"]"
  var message = issueMessage;
  var timeZone = "CET";
  var now = new Date();
  var startString = Utilities.formatDate(now, timeZone, 'MMMM dd, yyyy 17:30:00 Z');
  var startTime = new Date(startString);
  var endString = Utilities.formatDate(now, timeZone, 'MMMM dd, yyyy 17:35:00 Z');
  var endTime = new Date(endString); 

  // Create event for the issue
  var event = CalendarApp.getDefaultCalendar().createEvent(title, startTime, endTime, {description: message});

  // Add notification for the event, after deleting default notifications
  event.removeAllReminders();
  event.addPopupReminder(330);

  // Set status (to prevent blocking the day ; workaround as we can't modify transparency of the event)
  // event.addGuest("an-email@goes.here");
  // event.setMyStatus(CalendarApp.GuestStatus.INVITED);

}

1 Ответ

2 голосов
/ 08 января 2020

Похоже, вы создали триггер для функции createIssueReminder. Когда триггер вызывает функцию, он передает объект события. См. https://developers.google.com/apps-script/guides/triggers/events.

Поэтому, когда триггер вызывает createIssueReminder, он передает объект события как categories. Ваш код устанавливает categories только если он не был передан в качестве аргумента.

В случае триггера он передается.

Измените свою функцию следующим образом:

function createIssueReminder() {
  categories = ["S", "DD", "D", "M"];
...
...