iT邦幫忙

2021 iThome 鐵人賽

DAY 11
0
自我挑戰組

從無到有打造驗證碼共享的 Line 機器人系列 第 11

幫 Line Bot 加上身份驗證(2)

昨天成功得到10組不重複的亂數驗證碼,今天要把產好的驗證碼寫進 Google Sheet。

新增一張工作表 verification_code

先前提過,Google Sheet 可以看作是 Database,而裡面的工作表可以看成是 table,所以我們就在之前的 auto-get-verification-code Google Sheet 新增ㄧ張工作表叫 verification_code
add 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 以寫入 Google Sheet

接著修改 generateVerificationCode.gs 如下:

  • 將驗證碼 push 進 verificationCode[] 時,改成塞入 array [front+end],這是因為我們要塞進 Google Sheet 時,每一個驗證碼就塞一個 Row
  • 新增一個 insertVerificationCode function,利用 ReadMailAndInsertToGoogleSheet 連線到 verification_code sheet,並且將驗證碼寫入 Google Sheet
function 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 看看結果:
generateVerificationCode Result
有成功寫入驗證碼了!

今天就先到這裡~補班是身體跟心靈的雙重打擊啊(倒)
希望明天颱風可以平安無事!明天假日再來多完成一些進度囉~


上一篇
幫 Line Bot 加上身份驗證(1)
下一篇
幫 Line Bot 加上身份驗證(3)
系列文
從無到有打造驗證碼共享的 Line 機器人30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言