-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
68 lines (58 loc) Β· 1.89 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from flask import Flask, request
import json
import numpy as np
from linebot.models import TextSendMessage, StickerSendMessage
from linebot.models.template import *
from linebot import LineBotApi
from dotenv import dotenv_values
from utils import build_chatbot
config = dotenv_values('.env')
user_history = dict()
line_bot_api = LineBotApi(config["LINE_ACCESS_TOKEN"])
app = Flask(__name__)
@app.route('/')
def index():
return "Hello World!"
@app.route('/webhook', methods=['POST'])
def callback():
json_line = request.get_json(force=False,cache=False)
json_line = json.dumps(json_line)
decoded = json.loads(json_line)
no_event = len(decoded['events'])
for i in range(no_event):
event = decoded['events'][i]
event_handle(event)
return '',200
def event_handle(event):
try:
userId = event['source']['userId']
except:
print('error cannot get userId')
return ''
try:
rtoken = event['replyToken']
except:
print('error cannot get rtoken')
return ''
try:
msgId = event["message"]["id"]
msgType = event["message"]["type"]
except:
print('error cannot get msgID, and msgType')
sk_id = np.random.randint(1,17)
replyObj = StickerSendMessage(package_id=str(1),sticker_id=str(sk_id))
line_bot_api.reply_message(rtoken, replyObj)
return ''
if msgType == "text":
msg = str(event["message"]["text"])
userId = event['source']['userId']
ai_msg = build_chatbot(userId, msg, user_history)
ai_replyObj = TextSendMessage(text=ai_msg)
line_bot_api.reply_message(rtoken, ai_replyObj)
else:
sk_id = np.random.randint(1,17)
replyObj = StickerSendMessage(package_id=str(1),sticker_id=str(sk_id))
line_bot_api.reply_message(rtoken, replyObj)
return ''
if __name__ == '__main__':
app.run(debug=True)