GASでGoogle driveのファイルをGCSに転送

1.GCPでサービスアカウントキーを発行

Google DriveのファイルをGCSに転送するため、Google Cloudからサービスアカウントのキーを発行する必要があります。もしGoogle Cloudのアカウントを持っていないであれば、Google Cloudのサインインから初めてください。

まず、以下の流れで、専用のサービスアカウントを発行します。

以下のロールを付与します

ロール付与後、サービスアカウントのキーを発行して、JOSNとして保存します。

2.GASで転送を設定する

まずGASで必要なライブラリをインポートします。スクリプトIDは以下です

1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF
JavaScript

ライブラリを追加します。

上記設定後、以下のコードを使って転送を設定できます

function notifySlack(message, webhookUrl) {
  var payload = JSON.stringify({ 'text': message });
  var options = {
    'method': 'post',
    'contentType': 'application/json',
    'payload': payload
  };
  
  // Send the request to the Slack webhook URL
  var response = UrlFetchApp.fetch(webhookUrl, options);
  
  // Check the response code and throw an error if the request failed
  if (response.getResponseCode() !== 200) {
    throw new Error('Request to Slack returned an error: ' + response.getResponseCode() + ', response: ' + response.getContentText());
  }
}


function myFunction() {
  //サービスアカウントのキーをここにコピーする
  const service_account = {
  "type": "service_account",
  "project_id": "aaaaaaa",
  }

  const getStorageService = () =>
    OAuth2.createService('FirestoreStorage')
      .setPrivateKey(service_account.private_key)
      .setIssuer(service_account.client_email)
      .setPropertyStore(PropertiesService.getUserProperties())
      .setCache(CacheService.getUserCache())
      .setTokenUrl('https://oauth2.googleapis.com/token')
      .setScope('https://www.googleapis.com/auth/devstorage.read_write');


  // get yesterday date
  var date = new Date();
  date.setDate(date.getDate() - 1);
  var yesterday = Utilities.formatDate(date, "JST", "yyyyMMdd");
  console.log(yesterday);

  // input the file name rule
  var fileNamePrefix = "前日購入者情報" + yesterday;

  // get the file from folder id
  var G_DRIVE_FOLDER_ID = "1IKR5pv1_RM";
  const folder = DriveApp.getFolderById(G_DRIVE_FOLDER_ID); // access to folder
  const filesIterator = folder.getFiles(); // get all files from folder

  let file;
  while (filesIterator.hasNext()) {
    let currentFile = filesIterator.next();
    // get the file with name rule
    if (currentFile.getName().indexOf(fileNamePrefix) === 0) {
      file = currentFile; // find the file
      break;
    }
  }

  if (!file) {
    Logger.log('No file found for the latest date.');
    return;
  }
  console.log(file.getName());

  // Replace these with your own values
  const STORAGE_BUCKET = 'client';
  const FILE_PATH = 'purchase_log';

  const uploadFileToCloudStorage = () => {
  const blob = file.getBlob();
  const bytes = blob.getBytes();

  const API = `https://www.googleapis.com/upload/storage/v1/b`;
  const location = encodeURIComponent(`${FILE_PATH}/${file.getName()}`);
  const url = `${API}/${STORAGE_BUCKET}/o?uploadType=media&name=${location}`;

  const service = getStorageService();
  const accessToken = service.getAccessToken();

  const response = UrlFetchApp.fetch(url, {
    method: 'POST',
    contentLength: bytes.length,
    contentType: blob.getContentType(),
    payload: bytes,
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  });

  const result = JSON.parse(response.getContentText());
  Logger.log(JSON.stringify(result, null, 2));
  };





  uploadFileToCloudStorage();
  notifySlack(':party_blob: ', 'https://hooks.slack.com/services/');
  
}

JavaScript

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注