Guía de inicio rápido de Google Apps Script

En las guías de inicio rápido, se explica cómo configurar y ejecutar una app que llama a una API de Google Workspace.

Las guías de inicio rápido de Google Workspace usan las bibliotecas cliente de la API para manejar algunos detalles del flujo de autenticación y autorización. Te recomendamos que uses las bibliotecas cliente para tus propias apps. En esta guía de inicio rápido, se usa un enfoque de autenticación simplificado apropiado para un entorno de pruebas. En el caso de un entorno de producción, te recomendamos obtener información sobre la autenticación y la autorización antes de elegir las credenciales de acceso adecuadas para la app.

Crea una Google Apps Script que realice solicitudes a la API de actividad de Google Drive.

Objetivos

  • Crea la secuencia de comandos.
  • Habilita la API de actividad de Google Drive.
  • Ejecuta la muestra.

Requisitos previos

  • Una Cuenta de Google
  • Acceso a Google Drive

Crea la secuencia de comandos

  1. Para crear una secuencia de comandos nueva, ve a script.google.com/create.
  2. Reemplaza el contenido del editor de secuencia de comandos con el siguiente código:

drive/activity-v2/quickstart.gs
/**
 * Lists 10 activity for a Drive user.
 * @see https://developers.google.com/drive/activity/v2/reference/rest/v2/activity/query
 */
function listDriveActivity() {
  const request = {
    pageSize: 10
    // Use other parameter here if needed.
  };
  try {
    // Activity.query method is used Query past activity in Google Drive.
    const response = DriveActivity.Activity.query(request);
    const activities = response.activities;
    if (!activities || activities.length === 0) {
      console.log('No activity.');
      return;
    }
    console.log('Recent activity:');
    for (const activity of activities) {
      // get time information of activity.
      const time = getTimeInfo(activity);
      // get the action details/information
      const action = getActionInfo(activity.primaryActionDetail);
      // get the actor's details of activity
      const actors = activity.actors.map(getActorInfo);
      // get target information of activity.
      const targets = activity.targets.map(getTargetInfo);
      // print the time,actor,action and targets of drive activity.
      console.log('%s: %s, %s, %s', time, actors, action, targets);
    }
  } catch (err) {
    // TODO (developer) - Handle error from drive activity API
    console.log('Failed with an error %s', err.message);
  }
}

/**
 * @param {object} object
 * @return {string}  Returns the name of a set property in an object, or else "unknown".
 */
function getOneOf(object) {
  for (const key in object) {
    return key;
  }
  return 'unknown';
}

/**
 * @param {object} activity Activity object.
 * @return {string} Returns a time associated with an activity.
 */
function getTimeInfo(activity) {
  if ('timestamp' in activity) {
    return activity.timestamp;
  }
  if ('timeRange' in activity) {
    return activity.timeRange.endTime;
  }
  return 'unknown';
}

/**
 * @param {object} actionDetail The primary action details of the activity.
 * @return {string} Returns the type of action.
 */
function getActionInfo(actionDetail) {
  return getOneOf(actionDetail);
}

/**
 * @param {object} user The User object.
 * @return {string}  Returns user information, or the type of user if not a known user.
 */
function getUserInfo(user) {
  if ('knownUser' in user) {
    const knownUser = user.knownUser;
    const isMe = knownUser.isCurrentUser || false;
    return isMe ? 'people/me' : knownUser.personName;
  }
  return getOneOf(user);
}

/**
 * @param {object} actor The Actor object.
 * @return {string} Returns actor information, or the type of actor if not a user.
 */
function getActorInfo(actor) {
  if ('user' in actor) {
    return getUserInfo(actor.user);
  }
  return getOneOf(actor);
}

/**
 * @param {object} target The Target object.
 * @return {string} Returns the type of a target and an associated title.
 */
function getTargetInfo(target) {
  if ('driveItem' in target) {
    const title = target.driveItem.title || 'unknown';
    return 'driveItem:"' + title + '"';
  }
  if ('drive' in target) {
    const title = target.drive.title || 'unknown';
    return 'drive:"' + title + '"';
  }
  if ('fileComment' in target) {
    const parent = target.fileComment.parent || {};
    const title = parent.title || 'unknown';
    return 'fileComment:"' + title + '"';
  }
  return getOneOf(target) + ':unknown';
}

  1. Haz clic en Guardar .
  2. Haz clic en Proyecto sin título, escribe Guía de inicio rápido y haz clic en Cambiar nombre.

Habilita la API de actividad de Google Drive

  1. Abre el proyecto Apps Script.
  2. Haz clic en Editor .
  3. Junto a Servicios, haz clic en Agregar un servicio .
  4. Selecciona Drive Activity API y haz clic en Add.

Ejecutar la muestra

En el editor de Apps Script, haz clic en Ejecutar.

La primera vez que ejecutes la muestra, se te solicitará que autorices el acceso:

  1. Haz clic en Revisar permisos.
  2. Elige una cuenta.
  3. Haz clic en Permitir.

El registro de ejecución de la secuencia de comandos aparece en la parte inferior de la ventana.

Próximos pasos