三小時內做出 Line 自動點餐機器人

王詠翔,Yung-Hsiang Wang (Richard)

Last updated on

All rights reserved.

1. 簡介

這份教學示範如何在三小時內完成一個 Line 自動點餐機器人。流程主要分為三部分:建立 LINE Bot、設計 Google 表單、撰寫 Google Apps Script 處理訂單。

2. 設置 LINE 開發者帳號與建立 LINE Bot

要讓使用者能透過 LINE 與系統互動,必須先建立 LINE Bot。

2.1 註冊 LINE 開發者帳號

進入 LINE Developers 註冊並建立一個帳號。

2.2 建立 Provider 與 Channel

Provider 相當於應用的群組名稱,每個 Provider 下可以建立多個 Channel。

2.3 啟用 Messaging API

選擇「Messaging API」作為 Channel 類型,這樣才能讓機器人傳送與接收訊息。

2.4 取得 Access Token 與 Channel Secret

這些金鑰會在程式裡用來驗證身分與發送訊息。

2.5 配置 Webhook URL

Webhook 讓 LINE 能把使用者訊息轉送到我們的後端程式。

3. 創建 Google 表單訂單系統

我們利用 Google 表單收集訂單,並用 Google Sheets 保存資料。

3.1 設計 Google 表單

表單欄位建議包含:姓名、電話、LINE 認證碼、餐點內容。

3.2 與 Google Sheets 連結

每份表單提交後會自動記錄到試算表,方便後續處理。

3.3 自動化資料處理

透過 Google Apps Script 監聽表單提交事件,實現即時反應。

4. 實做 Google Apps Script

在 Google Sheets 的 Apps Script 編輯器中撰寫程式,實現資料處理與發送 LINE 訊息。

4.1 接收表單資料

使用 onFormSubmit 事件,抓取使用者輸入的電話、LINE 認證碼等。

4.2 產生訂單編號

function getOrderNumber(date, phoneNumber, orderDetail)
{
  return generateHashDateString(date, phoneNumber, orderDetail);
}

這裡會使用 hashCode 來生成短而唯一的訂單編號。

function hashCode(str)
{
  let hash = 0;
  for (let i = 0; i < str.length; i++)
  {
    const char = str.charCodeAt(i);
    hash = (hash << 5) - hash + char;
    hash |= 0;
  }
  hash = hash > 0 ? hash : -hash;
  return hash.toString(16).slice(-3);
}

4.3 發送確認訊息

function sendLineMessage(message, userID)
{
  const url = "https://api.line.me/v2/bot/message/push";

  const payload =
  {
    to: userID,
    messages: [{ type: "text", text: message }]
  };

  const options =
  {
    method: "post",
    headers:
    {
      "Content-Type": "application/json",
      Authorization: `Bearer ${LINE_TOKEN}`
    },
    payload: JSON.stringify(payload)
  };

  UrlFetchApp.fetch(url, options);
}

5. Google 表單回應處理

當使用者提交訂單時,Apps Script 會自動處理並回覆 LINE 訊息。

function onFormSubmit(e)
{
  try
  {
    const responses = e.namedValues;
    const userID = responses["LINE認證碼"][0];
    const userPhone = responses["連絡電話"][0];
    const orderDetail = "瓦斯訂購內容";

    const message = "訂單成立!編號:" + getOrderNumber("2025/01/24", userPhone, orderDetail);
    sendLineMessage(message, userID);
  }
  catch (err)
  {
    console.error("處理表單回應時出錯:", err);
  }
}

6. 附錄

完整程式碼可參考以下連結:

Google Apps Script Code