昨天成功得到10組不重複的亂數驗證碼,今天要把產好的驗證碼寫進 Google Sheet。
verification_code先前提過,Google Sheet 可以看作是 Database,而裡面的工作表可以看成是 table,所以我們就在之前的 auto-get-verification-code Google Sheet 新增ㄧ張工作表叫 verification_code。
注意:記得把第一行的資料格式設成純文字,驗證碼塞入後才不會被誤判為數字類型
Read Mail 專案接著我們修改一下 Read Mail 中的 connectToSheet.gs 以擴充使用情境
修改 connectToSheet.gs 如以下內容
sheetName 可用 sheet name 取得指定的工作表function connectToSheet(sheetName) {
  Logger.log('start to connectToSheet');
  var spreadSheet = SpreadsheetApp.openById('your_spread_sheet_id');
  var sheet = spreadSheet.getSheetByName(sheetName);
  if (sheet != null) {
    return sheet;
  }
  throw Error;
}
接著修改 app.gs 中有用到 connectToSheet 的地方
function app(userId) {
  var content = readMail();
  var sheet = connectToSheet('contents');
  insertToSheet(sheet, content, userId);
  return content;
}
接著修改 generateVerificationCode.gs 如下:
verificationCode[] 時,改成塞入 array [front+end],這是因為我們要塞進 Google Sheet 時,每一個驗證碼就塞一個 RowinsertVerificationCode function,利用 ReadMailAndInsertToGoogleSheet 連線到 verification_code sheet,並且將驗證碼寫入 Google Sheetfunction generateVerificationCode() {
  var amount = 10;
  var verificationCode = [];
  var i = 0;
  var front = "";
  var end = "";
  while ( i < amount) {
    front =  (((1 + Math.random()) * 0x10000)|0).toString(16).substring(1);
    end =  (((1 + Math.random()) * 0x10000)|0).toString(16).substring(1);
    verificationCode.push([front+end]);
    i++;
  }
  var uniqueVerificationCode = [...new Set(verificationCode)];
  insertVerificationCode(uniqueVerificationCode);
}
function insertVerificationCode(uniqueVerificationCode) {
  var sheet = ReadMailAndInsertToGoogleSheet.connectToSheet('verification_code');
  var range = sheet.getRange(1, 1, uniqueVerificationCode.length, 1);
  range.setValues(uniqueVerificationCode);
}
修改後記得存檔!然後我們就執行 generateVerificationCode 看看結果:
有成功寫入驗證碼了!
今天就先到這裡~補班是身體跟心靈的雙重打擊啊(倒)
希望明天颱風可以平安無事!明天假日再來多完成一些進度囉~