LINE 提供服務,先到 LINE Develpers 登入及註冊。
先到 https://developers.line.biz/en/ 登入
登入後,注册,填寫 Name 、Email,並發送信箱認證信
選擇要使用的服務: Messaging API for python。
Create new channel
完成相關資料輸入 => App icon、App name、Description、Category、 Subcategory、 Email address、 Privacy Policy URL、 Terms Of Use URL
Confirm:確認輸入資料正確性
channel 建立成功
Messaging settings:
Use webhooks 切換成 Enabled
Webhook URL :先留空白,等建立 Webhook URL 後,再回頭設定
這邊不用設定,最下面有 chatbot 的 QR code ,用於加入用户进行对话。
佈署到 heroku
在專案資料夾新增名稱為 Procfile 的檔案
web: node app.js
如果電腦有安裝 heroku CLI,則可以於專案資料夾路徑執行下面指令:
heroku login
會與連結到 heroku 網站,點選 log in 再回到 CLI,已登入 heroku
建立一個 heroku app
heroku create
成功建立,左邊是 app 網址,右邊是 git push 位址
可用 git remote -v 指令來查詢
將專案 push heroku master
git push heroku master
push 後,會偵測哪一種語言撰寫的 app、建置 runtime environment、Installing binaries、Installing dependencies(相關套件)
from __future__ import unicode_literals
import os
import sys
import redis
from argparse import ArgumentParser
from flask import Flask, request, abort
from linebot import (
LineBotApi, WebhookParser
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage, ImageMessage, VideoMessage, FileMessage, StickerMessage, StickerSendMessage, LocationMessage
)
from linebot.utils import PY3
app = Flask(__name__)
# get channel_secret and channel_access_token from your environment variable
channel_secret = os.getenv('LINE_CHANNEL_SECRET', None)
channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)
# obtain the port that heroku assigned to this app.
heroku_port = os.getenv('PORT', None)
if channel_secret is None:
print('Specify LINE_CHANNEL_SECRET as environment variable.')
sys.exit(1)
if channel_access_token is None:
print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')
sys.exit(1)
line_bot_api = LineBotApi(channel_access_token)
parser = WebhookParser(channel_secret)
@app.route("/callback", methods=['POST'])
def callback():
signature = request.headers['X-Line-Signature']
# get request body as text
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
# parse webhook body
try:
events = parser.parse(body, signature)
except InvalidSignatureError:
abort(400)
# if event is MessageEvent and message is TextMessage, then echo text
for event in events:
if not isinstance(event, MessageEvent):
continue
if isinstance(event.message, TextMessage):
handle_TextMessage(event)
if isinstance(event.message, ImageMessage):
handle_ImageMessage(event)
if isinstance(event.message, LocationMessage):
handle_LocationMessage(event)
if isinstance(event.message, VideoMessage):
handle_VideoMessage(event)
if isinstance(event.message, FileMessage):
handle_FileMessage(event)
if isinstance(event.message, StickerMessage):
handle_StickerMessage(event)
if not isinstance(event, MessageEvent):
continue
if not isinstance(event.message, TextMessage):
continue
return 'OK'
# Handler function for Text Message
def handle_TextMessage(event):
print(event.message.text)
msg = 'Do you want to know the latest news about the disease?'
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(msg)
)
# Handler function for Sticker Message
def handle_StickerMessage(event):
print(event.message.sticker_id)
msg = 'That is an interesting Sticker.'
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(msg)
)
# Handler function for Image Message
def handle_ImageMessage(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text="This photo has been stored successfully")
)
# Handler function for Location Message
def handle_LocationMessage(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text="I am sure your community does not have infected person.")
)
# Handler function for Video Message
def handle_VideoMessage(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text="Nice video!")
)
# Handler function for File Message
def handle_FileMessage(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text="Nice file!")
)
if __name__ == "__main__":
arg_parser = ArgumentParser(
usage='Usage: python ' + __file__ + ' [--port <port>] [--help]'
)
arg_parser.add_argument('-d', '--debug', default=False, help='debug')
options = arg_parser.parse_args()
app.run(host='0.0.0.0', debug=options.debug, port=heroku_port)