想法
Line BOT學習筆記,過程:取得MessageEvent輸入的字串並將字串代入到模板的Postback,在使用PostbackEvent 取得模板發送的Postbcak的字串,對PostbackEvent使用切片方式取得字串結果。
使用Python的Flask模組
程式碼
模板
放在@handler.add(MessageEvent, message=TextMessage) 之上
def test(keyword):
flex_message = FlexSendMessage(
alt_text='hello',
contents={
"type": "bubble",
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": "hello, world"
}
]
},
"footer": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "button",
"action": {
"type": "postback",
"label": "action",
"data": "測試hello{}".format(keyword),
"displayText": "測試{}".format(keyword)
}
}
]
}
}
)
return flex_message
MessageEvent
放在@handler.add(MessageEvent, message=TextMessage) 之下
import re
if re.search(r'測試$', event.message.text.lower()) != None:
#我好肥 測試
keyword = event.message.text[:-2] #我好肥
print(keyword)
abc = test(keyword) #call模板 並代入切片後的字串
line_bot_api.reply_message(event.reply_token, abc)
return 0
postbackEvent
放在@handler.add(PostbackEvent) 之下
def handle_postback(event):
ts = event.postback.data
print(ts)
keyword = ts[7:]
print(keyword)
if ts[7:] == '{}'.format(keyword):
text_message = TextSendMessage(text='訊息{}'.format(keyword))
line_bot_api.reply_message(event.reply_token, text_message)