Build Your Own Custom Short URL

最近在幫老婆做小工具時突然的靈感,可以透過 Line Bot + Google Apps Script + Github Issue 完成屬於自己的短網址服務。

實作 Link to heading

設定 Line Bot 讀訊息 Link to heading

參考 實作 LINE 聊天機器人 ( Google Apps Script )兩小時打造簡單 Line Chatbot — 使用 Google Apps Script & Google Sheet API 就可以。

Warning
記得在 回應功能 中關掉 聊天自動回應,不然你的機器人不會自動已讀。

產生短網址 Link to heading

想法來自於用 Github Issue 寫 Blog,可以 fork 這份專案,再參考 這篇index.html 加入下面這段即可。

<meta http-equiv="refresh" content="0; url=http://example.com/" />

然後再於 Google Apps Script 內透過 API 產生 Issue 獲得短網址並讓 Line Bot 回傳。

function getShortUrl(r) {
  let url = 'https://api.github.com/repos/{OWNER}/{REPO}/issues';

  let data = {
    "title": r.title,
    "body": r.link,
  }

  let token = PropertiesService.getScriptProperties().getProperty('<YOUR-TOKEN-KEY>');

  let requestOptions = {
    method: 'post',
    headers: {
      'Accept': 'application/vnd.github+json',
      'Authorization': 'Bearer ' + token,
    },
    payload: JSON.stringify(data),
    muteHttpExceptions: true,
    followRedirects: true
  };
  let n = JSON.parse(UrlFetchApp.fetch(url, requestOptions)).number;
  return 'https://{OWNER}.github.io/{REPO}/?' + n;
}
Tip
  1. 在執行 POST issue 遇到問題,參考了 How to post via API from google scripts,加入 muteHttpExceptions: true,
  2. 參考 How to define global variable in Google Apps Script 的作法,其中設定位置在 齒輪 => 指令碼屬性

後記 Link to heading

  1. 沒使用 GCP(Google Cloud Platform) debug,而是用土炮法建立一個 debug 用的 google sheet,然後訊息寫進去。
    function debug(cell, value) {
       let ss = SpreadsheetApp.openById("<sheet id>");
       let rs = ss.getSheetByName("<sheet name>");  
       rs.getRange(cell).setValue(value);
    }
    
  2. 這篇 Google App Script到底是什麼? 提供了新手會踩的雷。 😝
    • doGet,doPost 背就對了!
    • Latest Version (Head) 的 API 是測試部屬作業,但 Messaging API 的 Webhook 套用它測試會失敗。
  3. 其實 Line Bot 只要能完成 回傳你打的字,剩下的就是創造力!🥂