Não consigo executar o Google Apps Script no meu Gmail

Oct 01 2020

Eu segui o script postado em Alguma forma de enviar resposta automática do Gmail em determinados horários da semana? . No entanto, minha conta do Gmail não respondeu nenhuma mensagem fora do horário de trabalho de acordo com meu teste atual.

Eu fiz algo errado ou incompleto?

O que eu fiz:

  1. Criou um script em https://script.google.com/ por meio de copiar e colar.
  2. Salvei o script e testei. Funcionou bem. insira a descrição da imagem aqui
function myFunction() {
  function autoReply() {
var interval = 5;    //  if the script runs every 5 minutes; change otherwise
  var date = new Date();
  var day = date.getDay();
  var hour = date.getHours();
  if ([4,5,6,0].indexOf(day) > -1 || (day == 1 && hour < 9) || (day == 3 && hour >= 17)) {
    var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
    var threads = GmailApp.search('is:inbox after:' + timeFrom);
    for (var i = 0; i < threads.length; i++) {
      if (threads[i].isUnread()){
      threads[i].reply("xxxx");
      threads[i].markRead();
      threads[i].markImportant();
      }
    }
  }
}
}
  1. Ativado a API do Gmail por meio do menu "Serviços avançados do Google" insira a descrição da imagem aqui
  2. Configure um gatilho para o script a cada 5 minutos. insira a descrição da imagem aqui
  3. Enviou vários e-mails de teste de outra conta do Gmail para ver se haveria uma resposta automática.
  4. Não modificou manualmente nenhum e-mail recebido de outra conta.

Qualquer dica será muito apreciada!

Atualização: Eu me pergunto por que o seguinte script em si resultará em um erro "Função de script não encontrada: myFunction"?

function autoReply() {
  
  // find calendar event
  var today = new Date();
  var events = CalendarApp.getDefaultCalendar().getEventsForDay(today, { search: 'OOF' });
  var unavailableToday = false;
  for (var i = 0; i < events.length; i++) {
    
    if(events[i].isAllDayEvent() && events[i].isOwnedByMe()) {
      
      unavailableToday = true;
      break;
      
    }
    
  }
  
  var myEmail = Session.getEffectiveUser().getEmail();
  
  Logger.log('unavailableToday');
  Logger.log(unavailableToday);
  if(unavailableToday === true) {
    
    // get html message
    var files = DriveApp.getRootFolder().getFilesByName('autoreply.html');
    var htmlbody;
    while (files.hasNext()) {
      var file = files.next();

      htmlbody = file.getBlob().getDataAsString('utf8');
      
    }
   
    // get emails
    var interval = 2;
    var date = new Date();
    var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
    var threads = GmailApp.search('is:inbox !label:autoresponded after:' + timeFrom);
    var label = GmailApp.getUserLabelByName("autoresponded");

    for (var i = 0; i < threads.length; i++) {
      
      var message = threads[i].getMessages()[0];
      if (message.getFrom().indexOf(myEmail) < 0 && message.getFrom().indexOf("no-repl") < 0 && message.getFrom().indexOf("bounce") < 0 && message.getFrom().indexOf("spam") < 0) {
        
        Logger.log("Replied now");
        
        // reply
        threads[i].reply("", {
          htmlBody: htmlbody
        });
        
        // label
        label.addToThread(threads[i]);
        
      }
      
    }
    
  }
  
}

O que me fez pensar que MyFunction {} é essencial?

Respostas

3 RafaGuillermo Oct 01 2020 at 15:29

Responder:

Você precisa remover a autoReply()função de fora de myFunction()e definir o gatilho autoReply().

Mais Informações:

O código deve ser semelhante ao da resposta que você vinculou:

function autoReply() {
  var interval = 5;    //  if the script runs every 5 minutes; change otherwise
  var date = new Date();
  var day = date.getDay();
  var hour = date.getHours();
  if ([5,6,0].indexOf(day) > -1 || (day == 1 && hour < 8) || (day == 4 && hour >= 17)) {
    var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
    var threads = GmailApp.search('is:inbox after:' + timeFrom);
    for (var i = 0; i < threads.length; i++) {
      threads[i].reply("I am out of office. Your email will not seen until Monday morning.");
    }
  }
}

NÃO assim:

function myFunction() {
  function autoReply() {
    var interval = 5;    //  if the script runs every 5 minutes; change otherwise
    var date = new Date();
    var day = date.getDay();
    var hour = date.getHours();
    if ([5,6,0].indexOf(day) > -1 || (day == 1 && hour < 8) || (day == 4 && hour >= 17)) {
      var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
      var threads = GmailApp.search('is:inbox after:' + timeFrom);
      for (var i = 0; i < threads.length; i++) {
        threads[i].reply("I am out of office. Your email will not seen until Monday morning.");
      }
    }
  }
}

autoReply()não está sendo chamado quando você liga myFunction(), apenas declarado.

Você precisará editar o código e, em seguida, reconfigurar o gatilho para ser executado autoReply().

De w3schools :

As funções declaradas não são executadas imediatamente. Eles são "salvos para uso posterior" e serão executados mais tarde, quando forem invocados (chamados).

Espero que isso seja útil para você!

Referências:

  • Definições de função JavaScript - w3schools