-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathline_chatbot_reply.py
More file actions
112 lines (91 loc) · 3.48 KB
/
line_chatbot_reply.py
File metadata and controls
112 lines (91 loc) · 3.48 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import json
from flask import Flask, request, abort
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, PostbackEvent,
TextSendMessage, TemplateSendMessage,
TextMessage, ButtonsTemplate,
PostbackTemplateAction, MessageTemplateAction,
URITemplateAction,
)
app = Flask(__name__)
line_bot_api = LineBotApi('YOUR_CHANNEL_ACCESS_TOKEN')
handler = WebhookHandler('YOUR_CHANNEL_SECRET')
@app.route("/callback", methods=['POST'])
def callback():
# get X-Line-Signature header value
signature = request.headers['X-Line-Signature']
# get request body as text
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
# handle webhook body
try:
handler.handle(body, signature)
except InvalidSignatureError:
abort(400)
return 'OK'
@handler.add(PostbackEvent)
def handle_post_message(event):
# can not get event text
print("event =", event)
line_bot_api.reply_message(
event.reply_token,
TextMessage(
text=str(str(event.postback.data)),
)
)
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
print("event =", event)
if event.message.text == "查詢個人檔案":
user_id = event.source.user_id
profile = line_bot_api.get_profile(user_id, timeout=None)
line_bot_api.reply_message(
event.reply_token,
TextMessage(
text=str(profile),
)
)
else:
button_template_message =ButtonsTemplate(
thumbnail_image_url="https://i.imgur.com/eTldj2E.png?1",
title='Menu',
text='Please select',
image_size="cover",
actions=[
# PostbackTemplateAction 點擊選項後,
# 除了文字會顯示在聊天室中,
# 還回傳data中的資料,可
# 此類透過 Postback event 處理。
PostbackTemplateAction(
label='查詢個人檔案顯示文字-Postback',
text='查詢個人檔案',
data='action=buy&itemid=1'
),
PostbackTemplateAction(
label='不顯示文字-Postback',
text = None,
data='action=buy&itemid=1'
),
MessageTemplateAction(
label='查詢個人檔案-Message', text='查詢個人檔案'
),
]
)
line_bot_api.reply_message(
event.reply_token,
TemplateSendMessage(
alt_text="Template Example",
template=button_template_message
)
)
@app.route('/')
def homepage():
return 'Hello, World!'
if __name__ == "__main__":
app.run()