氣象機器人 (4) - 加入圖文選單和部署程式
在「氣象機器人 (1)~氣象機器人 (3)」的系列文章裡,已經完整實出 LINE 的氣象機器人,這篇教學會替氣象機器人新增圖文選單,只要點擊圖文選單的按鈕就能讓機器人快速提供氣象資訊,最後再將機器人部署到 Google Cloud Functions 裡,成為可以 24 小時運作不間斷的氣象機器人。
參考:
加入圖文選單
參考「建立圖文選單」教學,下載範例圖片放入 Google 雲端硬碟裡 ( 和 Colab 程式放在同一個目錄 )。
範例圖片:下載連結
接著依序輸入下列的程式碼,替 LINE 氣象機器人加入圖文選單,第一組程式碼,設定圖片與按鈕位置,產生圖文選單 id ( 輸入自己的 access token ):
import requests
import json
headers = {'Authorization':'Bearer 你的 access token','Content-Type':'application/json'}
body = {
'size': {'width': 2500, 'height': 640}, # 設定尺寸
'selected': 'true', # 預設是否顯示
'name': 'bbb', # 選單名稱
'chatBarText': 'b', # 選單在 LINE 顯示的標題
'areas':[ # 選單內容
{
'bounds': {'x': 0, 'y': 0, 'width': 1250, 'height': 640}, # 選單位置與大小
'action': {'type': 'uri', 'uri': 'https://line.me/R/nv/location/'} # 點擊後開啟地圖定位,傳送位置資訊
},
{
'bounds': {'x': 1251, 'y': 0, 'width':625, 'height': 640}, # 選單位置與大小
'action': {'type': 'message', 'text':'雷達回波圖'} # 點擊後傳送文字
},
{
'bounds': {'x': 1879, 'y': 0, 'width':625, 'height': 640}, # 選單位置與大小
'action': {'type': 'message', 'text':'地震資訊'} # 點擊後傳送文字
}
]
}
# 向指定網址發送 request
req = requests.request('POST', 'https://api.line.me/v2/bot/richmenu',
headers=headers,data=json.dumps(body).encode('utf-8'))
# 印出得到的結果
print(req.text)
第二組程式碼,將圖文選單綁定圖片 ( 輸入自己的 access token 和圖文選單 id ):
from linebot import LineBotApi, WebhookHandler
line_bot_api = LineBotApi('你的 access token')
with open("/content/drive/MyDrive/Colab Notebooks/line-bot-weather-demo.jpg", 'rb') as f:
line_bot_api.set_rich_menu_image("圖文選單 id", "image/jpeg", f)
第三組程式碼,將圖文選單與 LINE BOT 綁定 ( 輸入自己的 access token 和圖文選單 id ):
import requests
headers = {"Authorization":"Bearer 你的 access token", "Content-Type":"application/json"}
req = requests.request('POST', 'https://api.line.me/v2/bot/user/all/richmenu/圖文選單 id',
headers=headers)
print(req.text)
完成後,在氣象機器人的聊天畫面下方,就會出現圖文選單,點擊圖文選單,就會出現對應的動作。
部署程式到 Google Cloud Funcions
參考「使用 Google Cloud Functions」教學,進入 Google Cloud functions 並開啟一個新的專案,觸發條件勾選允許未經驗證的調用。
環境設定為 Python 3.7~3.9、進入點為 linebot。
點擊 requirements.txt,加入 line-bot-sdk 和 requests。
# Function dependencies, for example:
# package>=version
line-bot-sdk
requests
點擊 main.py,設定 import 函式庫。
from linebot import LineBotApi, WebhookHandler
from linebot.models import TextSendMessage, StickerSendMessage, ImageSendMessage, LocationSendMessage
import requests, statistics, json, time
下載並開啟範例程式,填入自己的 access token、channel secret 和氣象資料平台的授權碼,將 linebot 函式裡的程式碼移植到 Cloud Functions 裡,其他的函式也都依樣畫葫蘆的搬過去。
- 完整範例程式下載:line-bot-weather.py
完成後點擊部署,部署完成後前方會出現綠色打勾圖示。
點擊進入專案,點選「觸發條件」,複製觸發網址,回到 LINE Developer 控制台,將 Webhook 更新為觸發的網址。
驗證通過後,就完成了一個可以 24 小時運作的 LINE 氣象機器人。
小結
透過這系列的教學,就能打造出一個具有圖文選單,且能 24 小時運作的 LINE 氣象機器人,如果活用相關的技巧,就能讓機器人的功能更為強大囉!
意見回饋
如果有任何建議或問題,可傳送「意見表單」給我,謝謝~