简体   繁体   中英

How do I create a timeBased Add-on trigger that runs every hour?

Extension of my previous post here , I just figured this was more specific and should be it's own post.

Add-ons have restrictions on triggers. One such is that it can only run once an hour. I cannot figure out how to make that work.

Running the below script will produce the error: "attempted to perform an action that is not allowed" when it is run as an add-on. So if the below is not the proper add-on method for a once an hour script, what is, or did I find a bug?

ScriptApp.newTrigger('updateDay').timeBased().everyHours(1).create();

I tried adding the authorization check as Spencer suggested, and outlined in the documentation here . It passes the authentication, but still produces the same error.

function installTrigger(e) {
  var addonTitle = 'Lab Scheduler';
  var props = PropertiesService.getDocumentProperties();
  var authInfo = ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL);
  if (authInfo.getAuthorizationStatus() ==
      ScriptApp.AuthorizationStatus.REQUIRED) {
    var lastAuthEmailDate = props.getProperty('lastAuthEmailDate');
    var today = new Date().toDateString();
    if (lastAuthEmailDate != today) {
      if (MailApp.getRemainingDailyQuota() > 0) {
        var html = HtmlService.createTemplateFromFile('AuthorizationEmail');
        html.url = authInfo.getAuthorizationUrl();
        html.addonTitle = addonTitle;
        var message = html.evaluate();
        MailApp.sendEmail(Session.getEffectiveUser().getEmail(),
                          'Authorization Required',
                          message.getContent(), {
                            name: addonTitle,
                            htmlBody: message.getContent()
                          }
                         );
      }
      props.setProperty('lastAuthEmailDate', today);
    }
  } else {
    // Authorization has been granted, so continue to respond to the trigger.
    try{ 
      var as = SpreadsheetApp.getActiveSpreadsheet();
      var userTriggers = ScriptApp.getUserTriggers(as);
      var userTriggerL = userTriggers.length;
      if (userTriggers.length == 0){
        ScriptApp.newTrigger('updateDay').timeBased().everyHours(1).create();
      } 
    } catch(err){  
      catchToString_(err);  
    } // End try catch
  }
}

The issue you are running against is the scope of authorization your Add-on is running in when the trigger gets created or ran. Installed Triggers are run in AuthMode.FULL. You need to test for the current level of authorization before you can run the trigger. You use the ScriptApp.getAutorizationInfo(authMode) to get the status of the authMode the add-on is running in.

https://developers.google.com/apps-script/reference/script/script-app#getAuthorizationInfo(AuthMode)

Here is an example bit of code from the Apps Script documentation: https://github.com/googlesamples/apps-script-form-notifications-addon/blob/master/Code.gs

var authInfo = ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL);

  // Check if the actions of the trigger require authorizations that have not
  // been supplied yet -- if so, warn the active user via email (if possible).
  // This check is required when using triggers with add-ons to maintain
  // functional triggers.
  if (authInfo.getAuthorizationStatus() ==
  ScriptApp.AuthorizationStatus.REQUIRED) {
    // Re-authorization is required. In this case, the user needs to be alerted
    // that they need to reauthorize; the normal trigger action is not
    // conducted, since it authorization needs to be provided first. Send at
    // most one 'Authorization Required' email a day, to avoid spamming users
    // of the add-on.
sendReauthorizationRequest();
  } else {
    // All required authorizations has been granted, so continue to respond to
    // the trigger event.
  }

I think you are using the trigger for specific days at specific hour, so in your example you would need to specify the day (eg Mondays) and atHour(1) would make the trigger to run every monday at 1.

For specifying how often it should be triggered you would need to write: ScriptApp.newTrigger('myFunction').timeBased(). everyHours(1) .create();

I have come to the conclusion that this is a bug or .timebased() triggers are not supported as an add-on, (which I thought they were).

Please star this issue to help get this working again.

https://code.google.com/p/google-apps-script-issues/issues/detail?id=4524&q=.timeBased()%20add-on%20trigger&colspec=Stars%20Opened%20ID%20Type%20Status%20Summary%20Component%20Owner

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM