將 ChatGPT LineBot 部屬在 Google Scripts 上


Posted by WeiJ0 on 2023-03-28

前言

近期,應該是說前一陣子,常常可以看見很多人會將 OpenAI 的 GPT-3 模型,應用在 Line Message API 上,可以直接透過官方帳號來使用 ChatGPT,但部屬是需要費用的,而免費的 Vercel 卻可能會發生 TimeOut 的問題,後來終於找了一個 TimeOut 限制稍微長的地方部屬,就是 Google Scripts。

Github Repo


事前準備

  1. 取得 OPEN AI 的 API Key

    OPEN AI 的 API Key 在右上角的 Log in 進行登入,登入後原本右上角的地方會變你的帳號,點擊後會出現選單,再點選選單中的 View API Keys,就可以看到 API Key。

    這邊產生的 KEY 只會出現這次,所以要記得複製下來。否則就只能重新產生一次。

  2. 建立一個 Line Developer 及官方帳號

    前往 Line Developer 後台,登入 LINE 帳號後如果不是 developer 會需要再簡單輸入資料進行註冊。

    完成後會進入到開發者後台,沒有 provider 的話需要建立一個新的 provider,這個 provider 名稱不限。

    完成後會進入 provider 的頁面,這時候再新增一個 Messageing API,僅需要填寫必填欄位即可 (非 optional)

    建立後會進入 Messaging API 的後台頁面,接著將頁籤切換到 Messaging API,並複製最下方的 Channel access token

  3. 建立一個 Google Scripts 專案,直接選擇新專案,接著會進入 Google 新版的網頁程式編輯器中。緊接再右邊選單的最後一項 [專案設定] 最下方的指令碼屬性儲存上面取得的 API KEY 。

    屬性名稱可以不同,但在稍後的程式碼需要做微調。沒問題再回到編輯器頁面中將程式貼上

    function requestGPTApi(text) {
      const apiURL = 'https://api.openai.com/v1/completions'
      const params = {
        headers: { Authorization: 'Bearer ' + ScriptProperties.getProperty('OPENAI_KEY') },
        muteHttpExceptions: true,
        payload: JSON.stringify({ model: 'text-davinci-003', prompt: text, max_tokens: 400 }),
        contentType: 'application/json',
        method: 'post',
      }
      const response = UrlFetchApp.fetch(apiURL, params)
      const data = response.getContentText()
      const json = JSON.parse(data)
      return json.choices[0].text
    }
    
    function doPost(e) {
      const apiUrl = 'https://api.line.me/v2/bot/message/reply'
      const eventData = JSON.parse(e.postData.contents).events[0]
      const replyToken = eventData.replyToken
      const messageText = eventData.message.text
      const messageType = eventData.message.type
    
      let replyMessage = requestGPTApi(messageText)
      replyMessage = replyMessage.slice(2).replace('\n\n\n', '\n\n')
    
      const payload = {
        replyToken: replyToken,
        messages: [
          {
            type: 'text',
            text: replyMessage,
          },
        ],
      }
      const options = {
        payload: JSON.stringify(payload),
        method: 'POST',
        headers: { Authorization: 'Bearer ' + ScriptProperties.getProperty('LINE_ACCESS_TOKEN') },
        contentType: 'application/json',
      }
    
      UrlFetchApp.fetch(apiUrl, options)
    }
    

    在程式碼中會有需要 Token 的地方就直接用 ScriptProperties.getProperty('屬性名稱') 來取得,這邊的屬性名稱就是在專案設定中的指令碼屬性儲存的名稱。

    接著就進行部屬,右上角的部屬,選取類型選擇 [網頁應用程式],將誰可以存取選擇 [所有人],再按下部屬。

    部屬成功後再下方就會出現網頁應用程式的網址,再複製下來回到剛剛的 Line Message API 後台,將 Webhook URL 貼上。

    這時候可以按下 Verify 測試是否有成功,如果沒問題的話應該會返回 Success 訊息。

  4. 接著就可以到官方帳號下實際測試啦


#line message api #google scripts #openai #LINE Bot #Webhook







Related Posts

User Persona Analysis - H&M

User Persona Analysis - H&M

 TuriCreate

TuriCreate

React Native 手動換字型

React Native 手動換字型


Comments