目前的功能在還沒有導入NLP的功能之前,先利用關鍵字比對的方式該我們的LINEBOT 可以接收使用者的問題並且回覆對應的關係
1.1 到官方開發者網站以line帳號註冊並且取得自己的金鑰
channel_secret 等於比較短的那組金鑰
channel_access_token等於比較長的那組金鑰
今天先來增加時間查詢這個功能就好
套用datatime 套件from datetime import datetime
增加一個LIST,裡面放入使用者可能會詢問的字眼,位置放在@app.route之前
msgchk_timer =["現在時間","時間","目前時間","現在幾點?","報時"]
參考範例程式另一個APP 的做法,啟用@handler修飾器,用來回應訊息
並且建立自訂函式以符合flask 的功能處理的格式
def handle_text_message(event):
User_MSG = event.message.text
if User_MSG in msgchk_timer:
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
line_bot_api.reply_message(event.source.user_id, TextSendMessage(text=f"現在時間:{current_time}"))
else:
pass
特別注意到由於line 是以json格式傳回line server,因此我們必須以dict的資料格式回傳到line
server.例如像這樣{現在時間current_time}
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import unicode_literals
from datetime import datetime
import os
import sys
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,
)
app = Flask(__name__)
# get channel_secret and channel_access_token from your environment variable
channel_secret = os.getenv('your secret', None)
channel_access_token = os.getenv( 'your token', 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) # 來自LINE開發者網站提供的TOKEN
parser = WebhookParser(channel_secret) # 來自開發者網站提供的通道銷
"""
@app python 的修飾器,可以視為參考點
.route("/callback/",methods=['POST'])透過flask 框架註冊轉址路由的網路路由位置
在網址實際會變成 http://127.0.0.1/callback/
"""
msgchk_timer = ["現在時間", "時間", "目前時間", "現在幾點?", "報時"]
@app.route("/callback", methods=['POST'])
def callback():
signature = request.headers['X-Line-Signature'] # line的數位簽署 不能省略
# get request body as text #接收來自於使用者傳送的訊息
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
# parse webhook body# 處理json 格式的資料
try:
events = parser.parse(body, signature)
except InvalidSignatureError:
abort(400)
return 'OK' # 回覆傳輸狀況 OK == 200
@handler.add(MessageEvent, message=TextMessage)
def handle_text_message(event):
User_MSG = event.message.text
if User_MSG in msgchk_timer:
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
line_bot_api.reply_message(event.source.user_id, TextSendMessage(text=f"台北時間:{current_time}"))
else:
pass
# App 的執行區段設定
if __name__ == "__main__":
arg_parser = ArgumentParser(
usage='Usage: python ' + __file__ + ' [--port <port>] [--help]'
)
arg_parser.add_argument('-p', '--port', type=int, default=8000, help='port')
arg_parser.add_argument('-d', '--debug', default=True, help='debug')
options = arg_parser.parse_args()
app.run(debug=options.debug, port=options.port)