Ações da agenda

Os objetos Action permitem criar um comportamento interativo nos complementos do Google Workspace. Eles definem o que acontece quando um usuário interage com um widget (por exemplo, um botão) na interface do complemento.

Uma ação é anexada a um widget específico usando uma função de gerenciador de widgets, que também define a condição que aciona a ação. Quando acionada, a ação executa uma função de callback designada. A função de callback recebe um objeto de evento que transmite informações sobre as interações do usuário no lado do cliente. É necessário implementar a função de callback e fazer com que ela retorne um objeto de resposta específico.

Por exemplo, digamos que você queira um botão que crie e exiba um novo cartão quando clicado. Para isso, é necessário criar um novo widget de botão e usar a função de gerenciador setOnClickAction(action) para definir um Action de criação de cards. O Action definido especifica uma função de callback do Apps Script que é executada quando o botão é clicado. Nesse caso, você implementa a função de callback para criar o cartão que quer e retornar um objeto ActionResponse. O objeto de resposta instrui o complemento a exibir o cartão criado pela função de callback.

Nesta página, descrevemos as ações de widgets específicas do Agenda que você pode incluir no seu complemento.

Interações da agenda

Os complementos do Google Workspace que estendem o Agenda podem incluir algumas ações de widget específicas. Essas ações exigem a função de callback de ação associada para retornar objetos de resposta especializados:

Tentativa de ação A função de callback precisa retornar
Como adicionar participantes CalendarEventActionResponse
Como configurar dados de videoconferência CalendarEventActionResponse
Como adicionar anexos CalendarEventActionResponse

Para usar essas ações de widget e objetos de resposta, todas as condições a seguir precisam ser atendidas:

Além disso, as mudanças feitas pela função de callback da ação não são salvas até que o usuário salve o evento da Agenda.

Adicionar participantes com uma função de callback

O exemplo a seguir mostra como criar um botão que adiciona um participante específico a um evento da Agenda que está sendo editado:

  /**
   * Build a simple card with a button that sends a notification.
   * This function is called as part of the eventOpenTrigger that builds
   * a UI when the user opens an event.
   *
   * @param e The event object passed to eventOpenTrigger function.
   * @return {Card}
   */
  function buildSimpleCard(e) {
    var buttonAction = CardService.newAction()
        .setFunctionName('onAddAttendeesButtonClicked');
    var button = CardService.newTextButton()
        .setText('Add new attendee')
        .setOnClickAction(buttonAction);

    // Check the event object to determine if the user can add
    // attendees and disable the button if not.
    if (!e.calendar.capabilities.canAddAttendees) {
      button.setDisabled(true);
    }

    // ...continue creating card sections and widgets, then create a Card
    // object to add them to. Return the built Card object.
  }

  /**
   * Callback function for a button action. Adds attendees to the
   * Calendar event being edited.
   *
   * @param {Object} e The action event object.
   * @return {CalendarEventActionResponse}
   */
  function onAddAttendeesButtonClicked (e) {
    return CardService.newCalendarEventActionResponseBuilder()
        .addAttendees(["aiko@example.com", "malcom@example.com"])
        .build();
  }

Como definir dados de videoconferência com uma função de callback

Esta ação define os dados da videoconferência no evento aberto. Para esses dados de videoconferência, o ID da solução de videoconferência precisa ser especificado porque a ação não foi acionada pelo usuário que selecionou a solução desejada.

O exemplo a seguir mostra como criar um botão que define dados de conferência para um evento que está sendo editado:

  /**
   * Build a simple card with a button that sends a notification.
   * This function is called as part of the eventOpenTrigger that builds
   * a UI when the user opens a Calendar event.
   *
   * @param e The event object passed to eventOpenTrigger function.
   * @return {Card}
   */
  function buildSimpleCard(e) {
    var buttonAction = CardService.newAction()
        .setFunctionName('onSaveConferenceOptionsButtonClicked')
        .setParameters(
          {'phone': "1555123467", 'adminEmail': "joyce@example.com"});
    var button = CardService.newTextButton()
        .setText('Add new attendee')
        .setOnClickAction(buttonAction);

    // Check the event object to determine if the user can set
    // conference data and disable the button if not.
    if (!e.calendar.capabilities.canSetConferenceData) {
      button.setDisabled(true);
    }

    // ...continue creating card sections and widgets, then create a Card
    // object to add them to. Return the built Card object.
  }

  /**
   * Callback function for a button action. Sets conference data for the
   * Calendar event being edited.
   *
   * @param {Object} e The action event object.
   * @return {CalendarEventActionResponse}
   */
  function onSaveConferenceOptionsButtonClicked(e) {
    var parameters = e.commonEventObject.parameters;

    // Create an entry point and a conference parameter.
    var phoneEntryPoint = ConferenceDataService.newEntryPoint()
      .setEntryPointType(ConferenceDataService.EntryPointType.PHONE)
      .setUri('tel:' + parameters['phone']);

    var adminEmailParameter = ConferenceDataService.newConferenceParameter()
        .setKey('adminEmail')
        .setValue(parameters['adminEmail']);

    // Create a conference data object to set to this Calendar event.
    var conferenceData = ConferenceDataService.newConferenceDataBuilder()
        .addEntryPoint(phoneEntryPoint)
        .addConferenceParameter(adminEmailParameter)
        .setConferenceSolutionId('myWebScheduledMeeting')
        .build();

    return CardService.newCalendarEventActionResponseBuilder()
        .setConferenceData(conferenceData)
        .build();
  }

Adicionar anexos com uma função de callback

O exemplo a seguir mostra como criar um botão que adiciona um anexo a um evento do Google Agenda que está sendo editado:

  /**
   * Build a simple card with a button that creates a new attachment.
   * This function is called as part of the eventAttachmentTrigger that
   * builds a UI when the user goes through the add-attachments flow.
   *
   * @param e The event object passed to eventAttachmentTrigger function.
   * @return {Card}
   */
  function buildSimpleCard(e) {
    var buttonAction = CardService.newAction()
        .setFunctionName('onAddAttachmentButtonClicked');
    var button = CardService.newTextButton()
        .setText('Add a custom attachment')
        .setOnClickAction(buttonAction);

    // Check the event object to determine if the user can add
    // attachments and disable the button if not.
    if (!e.calendar.capabilities.canAddAttachments) {
      button.setDisabled(true);
    }

    // ...continue creating card sections and widgets, then create a Card
    // object to add them to. Return the built Card object.
  }

  /**
   * Callback function for a button action. Adds attachments to the Calendar
   * event being edited.
   *
   * @param {Object} e The action event object.
   * @return {CalendarEventActionResponse}
   */
  function onAddAttachmentButtonClicked(e) {
    return CardService.newCalendarEventActionResponseBuilder()
             .addAttachments([
               CardService.newAttachment()
                 .setResourceUrl("https://example.com/test")
                 .setTitle("Custom attachment")
                 .setMimeType("text/html")
                 .setIconUrl("https://example.com/test.png")
             ])
        .build();
  }

Como definir o ícone do anexo

O ícone do anexo precisa estar hospedado na infraestrutura do Google. Consulte Fornecer ícones de anexo para mais detalhes.