电子表格脚本/ nag电子邮件可以手动或分钟计时器运行,但不适用于日期计时器

时间:2012-07-11 01:06:48

标签: google-apps-script

这是一个益智游戏。我有一个谷歌电子表格。这意味着允许在线评估讲座。居民登录到关联的表单,然后填写。

伴随它是一个“唠叨”功能 - 第二张表检查他们的名字,跟踪他们是否已提交,如果没有,它会在一定时间(3天)过后发送一封唠叨的电子邮件。

脚本运行正常,我手动完成。如果我使用分钟计时器(即每10分钟运行一次)。

但是当我为我想要的东西设置脚本时 - 每天检查一次,它不会运行,我收到以下错误报告:

电子邮件无效:#N / A

这是特别奇怪的,因为我有其他类似的功能运行其他电子表格,他们一直工作。

我能想到的唯一不同之处就是我有几个类似的脚本在运行(每周一张)。我尝试将函数名称更改为唯一的,还将电子表格调用更改为openById,并将工作表变量更改为getSheetByName,以防多个类似的脚本彼此混淆。没有差异。

指向电子表格副本的链接位于https://docs.google.com/a/brown.edu/spreadsheet/ccc?key=0AkP6szc0nsS2dEItLXEwdjVsWUFpOTdjZUdtTlo4cGc#gid=0

我正在附加以下脚本(你会注意到我添加了错误报告,但它没有添加太多)。数据变量从教程中借用,而且该教程片段对我来说一直很好。

任何见解都将受到赞赏。

代码:

var SEMINAR_FORM_URL = "http://med.brown.edu/DPHB/training/psychiatry_general/secure/seminarevals/seminar_evals.html";
var YES = "YES";
var DISTRIBUTE = "robert_boland_1@brown.edu,robertboland11@gmail.com"; 

//This function sends out a nag to do the seminar evals including a link to the seminar form
//This is allowed when sheet 2 says "YES" to "Nag?"  
//Should not check more than once daily or will keep sending out and should be triggered AFTER the checkCoverageSubmit. 

function sendNag() {  
  try {
  var ss = SpreadsheetApp.openById("0AkP6szc0nsS2dDkwQTE0OVlPeWM5ZlJIenVKLU1pVVE");
  var sheet = ss.getSheetByName("Sheet2");
  var startRow = 2

  // getRowsData was reused from Reading Spreadsheet Data using JavaScript Objects tutorial
  var data = getRowsData(sheet);

  // For every Seminar report row
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    row.rowNumber = i + 2;    
    if (row.nag==YES) {   //sends the nag message below
     var message = "<HTML><BODY>"
    + "<P> THIS IS A REMINDER MESSAGE:"
    + "<P> For "  + row.name         
    + "<P> You still need to complete your seminar evaluations for" 
    + "<P> the seminars done on "+ row.dateOfSeminar
    + "<P>" 
    + "<P> It has been "+ row.daysElapsed + " days since the seminar." 
    + "<P>"     
    + '<P><b> Please fill out the evaluations.  You can find links to the evalutions on <A HREF="' + SEMINAR_FORM_URL + '"><b>HERE.</b></A>  Do this now!</b>.' 
    + "<P>"
    + "<P>" 
    + "<P>" 
    + "<P>--------------------------------------------------------"
    + "<P> <i>You are receiving this message because our records report that you have yet to complete a required seminar evaluations. </i>"
    + "<P> If you think this remind was sent in error, please <a href='mailto:robert_boland_1@brown.edu'><b>contact me</b></a> to prevent further nagging!"    
    + "<P>"     
    + "<P>_______________________________________________________________________________"
    + "</HTML></BODY>";
      if(row.name){  
      MailApp.sendEmail(row.name, "Reminder: Please complete your seminar evals!", "", {cc:DISTRIBUTE,htmlBody: message});
      } SpreadsheetApp.flush(); 
    } 
  }   

  } catch (e) {    
    MailApp.sendEmail("robert_boland_1@brown.edu", "Error report", e.message); 
  }
}

/////////////////////////////////////////////////////////////////////////////////
// Code reused from Reading Spreadsheet Data using JavaScript Objects tutorial //
/////////////////////////////////////////////////////////////////////////////////

// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
//   - sheet: the sheet object that contains the data to be processed
//   - range: the exact range of cells where the data is stored
//       This argument is optional and it defaults to all the cells except those in the first row
//       or all the cells below columnHeadersRowIndex (if defined).
//   - columnHeadersRowIndex: specifies the row number where the column names are stored.
//       This argument is optional and it defaults to the row immediately above range; 
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
  var headersIndex = columnHeadersRowIndex || range ? range.getRowIndex() - 1 : 1;
  var dataRange = range || 
    sheet.getRange(headersIndex + 1, 1, sheet.getMaxRows() - headersIndex, sheet.getMaxColumns());
  var numColumns = dataRange.getEndColumn() - dataRange.getColumn() + 1;
  var headersRange = sheet.getRange(headersIndex, dataRange.getColumn(), 1, numColumns);
  var headers = headersRange.getValues()[0];
  return getObjects(dataRange.getValues(), normalizeHeaders(headers));
}

// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
//   - data: JavaScript 2d array
//   - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
  var objects = [];
  for (var i = 0; i < data.length; ++i) {
    var object = {};
    var hasData = false;
    for (var j = 0; j < data[i].length; ++j) {
      var cellData = data[i][j];
      if (isCellEmpty(cellData)) {
        continue;
      }
      object[keys[j]] = cellData;
      hasData = true;
    }
    if (hasData) {
      objects.push(object);
    }
  }
  return objects;
}

// Returns an Array of normalized Strings. 
// Empty Strings are returned for all Strings that could not be successfully normalized.
// Arguments:
//   - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
  var keys = [];
  for (var i = 0; i < headers.length; ++i) {
    keys.push(normalizeHeader(headers[i]));
  }
  return keys;
}

// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
//   - header: string to normalize
// Examples:
//   "First Name" -> "firstName"
//   "Market Cap (millions) -> "marketCapMillions
//   "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
  var key = "";
  var upperCase = false;
  for (var i = 0; i < header.length; ++i) {
    var letter = header[i];
    if (letter == " " && key.length > 0) {
      upperCase = true;
      continue;
    }
    if (!isAlnum(letter)) {
      continue;
    }
    if (key.length == 0 && isDigit(letter)) {
      continue; // first character must be a letter
    }
    if (upperCase) {
      upperCase = false;
      key += letter.toUpperCase();
    } else {
      key += letter.toLowerCase();
    }
  }
  return key;
}

// Returns true if the cell where cellData was read from is empty.
// Arguments:
//   - cellData: string
function isCellEmpty(cellData) {
  return typeof(cellData) == "string" && cellData == "";
}

// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
  return char >= 'A' && char <= 'Z' ||
    char >= 'a' && char <= 'z' ||
    isDigit(char);
}

// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
  return char >= '0' && char <= '9';
}

1 个答案:

答案 0 :(得分:1)

请将您的错误解析为以下功能,以便我们获得更多信息,例如:行号。

/**
 * Parse errors stacktrace into a readable format.
 * This function never throws an error, so you don't need to try-catch it.
 * If the error cannot be processed, it will just return it silently.
 * @return {string} The error toString plus its stacktrack broke into multiple lines
 * @param {Error} e The error to be processed
 */
function parseErr(e) {
  try {
    var ret;
    if( e !== undefined && e !== null && e.stack && e.toString ) {
      ret = e.toString()+' \nStacktrace: \n';
      var stack = e.stack.replace(/\n/g,'').match(/:\d+( \([^\)]+\))?/g);
      for( var i in stack )
        ret += stack[i].replace(/[\(\):]/g,'').split(/ /).reverse().join(':') + ' \n';
    } else if( typeof(e) === 'object' )
      ret = inspect(ret);
    else
      ret = ''+e;
    return ret;
  } catch(suppress) {
    return ''+e;
  }
}

/**
 * Inspect an object properties and returns a nicely formatted string
 * Good to be logged or sent via email.
 * @return {string} inspection of the object's iterable elements
 * @param {*} o object to be inspected
 * @param {number=} optMaxLevel optional max level that function should go deep in the object
 *     Important to avoid infinite loops on recursive objects. Defaults to 4
 */
function inspect(o,optMaxLevel) {
  if( optMaxLevel === undefined )
    optMaxLevel = 4; //default inspect level
  else if( optMaxLevel < 1 )
    return '\n> maximum level must be equal to or greater than 1 (one)';
  if( o === null || o === undefined )
    return '\n> '+o;
  else {
    var tof = function(v) {
      try { return typeof(v); } //I don't now why typeof is throwing errors on arrays
      catch(e) { return 'object'; } //so I'm just defaulting to object
    };
    var ret = function innerInspect(o,maxLevel,level) {
      var msg = '';
      if( level.length > maxLevel ) {
        for( var i in o )
          msg += i+',';
        msg = '\n'+level+msg.substring(0,msg.length-1); //remove last comma
      } else {
        for( var i in o ) {
          var t = tof(o[i]);
          msg += '\n'+level+i+' :: '+t;
          try {
            if( t == 'object' && o[i] )
              msg += innerInspect(o[i],maxLevel,'>'+level);
            else if( t != 'function' )
              msg += ' = "'+o[i]+'"';
          } catch(e) {
            msg += '\n>'+level+e.message;
          }
        }
        if( msg == '' )
          msg = ' = "'+o.toString()+'"';
      }
      return msg;
    }(o,optMaxLevel+1,'> ');
    return ret.substring(0,2) == ' =' ? '\n> '+tof(o)+ret : ret;
  }
}

不仅仅发送自己e.message发送解析后的堆栈,甚至更好,也可以添加当前变量的一些值,例如:

var moreInfo = inspect({i:i, row:row}) + '\n' + parseErr(e);
MailApp.sendEmail("yourself@etc", "Error report", moreInfo);