新增
- 修改reply messages的邏輯。
- 新增reply messages的種類:文字、貼圖、圖片、影片、聲音、位置等。
主要針對Line Developers網站上message types進行介紹:
- Text message
- Sticker message
- Image message
- Video message
- Audio message
- Location message
- Imagemap message
- Template message
- Flex message
Text message
首先列出app.py
程式碼基本上如下,我們會針對handle_message
這個函數去做修改reply messages的功能,讓我們可以傳出不同種類的訊息。
import os
from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import *
app = Flask(__name__)
# 必須放上自己的Channel Access Token
line_bot_api = LineBotApi('********')
# 必須放上自己的Channel Secret
handler = WebhookHandler('*********')
# 使用Your user ID推播訊息
line_bot_api.push_message('********', TextSendMessage(text='你可以開始了'))
# 監聽所有來自 /callback 的 Post Request
@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(MessageEvent, message=TextMessage)
def handle_message(event):
# 訊息傳遞區塊
## 基本上針對不同種類訊息的編輯都在這裡 ##
pass
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
Text message就是最基本的純文字訊息,像下面這個例子就是返回使用者傳送訊息放入「你說…?」,例如A說:「吃早餐了」,line bot回:「你說吃早餐了?」
def handle_message(event):
message = event.message.text
text_message = TextSendMessage(text='你說'+message+'?')
line_bot_api.reply_message(event.reply_token, text_message)
這裡TextSendMessage
其實也有提供emojis參數讓你可以帶入表情貼圖在文字訊息中,下面這個例子就是,A說:「你好」,line bot回:「(H)(I)~你好我是Line Chatbot (moon big smile)」。表情貼圖可以在官方的emojis找到product id和emoji id。
def handle_message(event):
message = event.message.text
if any([ ele in message for ele in ['嗨','Hi', 'hi', '你好'] ]):
emoji = [
{
"index": 0,
"productId": "5ac21a8c040ab15980c9b43f",
"emojiId": "008"
},
{
"index": 1,
"productId": "5ac21a8c040ab15980c9b43f",
"emojiId": "009"
},
{
"index": 20,
"productId": "5ac1bfd5040ab15980c9b435",
"emojiId": "009"
}
]
text_message = TextSendMessage(text='$$~你好我是Line Chatbot $', emojis=emoji)
line_bot_api.reply_message(event.reply_token, text_message)
Sticker message
既然可以發表情貼圖,那是不是也可以發一般貼圖呢?當然沒問題,只要使用StickerSendMessage
搭配在官方的sticker找到的package id和sticker id。只是目前表情貼圖和一般貼圖僅能從官方提供的這幾個去選,無法使用商店購買的那些貼圖。
def handle_message(event):
message = event.message.text
if '範例貼圖' in message:
sticker_message = StickerSendMessage(
package_id='8525',
sticker_id='16581295'
)
line_bot_api.reply_message(event.reply_token, sticker_message)
Image message
接下來我們介紹照片訊息,使用ImageSendMessage
再放入網址(URL形式)就可以了。注意,這裡是使用圖片網址,然後透過Line API包裝起來傳出去,才是我們在訊息上看到的照片。
def handle_message(event):
message = event.message.text
if '範例圖片' in message:
image_message = ImageSendMessage(
original_content_url='https://i.ytimg.com/vi/vJO4Fg_iEss/maxresdefault.jpg',
preview_image_url='https://i.ytimg.com/vi/vJO4Fg_iEss/maxresdefault.jpg'
)
line_bot_api.reply_message(event.reply_token, image_message)
Video message
影片訊息使用的是VideoSendMessage
,也是將影片網址作為參數傳入即可。
def handle_message(event):
message = event.message.text
if '範例影片' in message:
video_message = VideoSendMessage(
original_content_url='https://i.imgur.com/wRjizMx.mp4',
preview_image_url='https://i.imgur.com/SqgLili.jpeg'
)
line_bot_api.reply_message(event.reply_token, video_message)
Audio message
聲音訊息使用的是AudioSendMessage
,也是將聲音網址作為參數傳入即可。其中duration是用來設定聲音檔長度(毫秒)。
def handle_message(event):
message = event.message.text
if '範例聲音' in message:
audio_message = AudioSendMessage(
original_content_url='https://r1---sn-q5q5uf-un5l.googlevideo.com/videoplayback?expire=1662714295&ei=V60aY_bkCtOdvcAP85S2-A8&ip=35.234.62.252&id=o-APYPB7PTiYPK7vQRVIEl-H7HDaVVFls5HBoy5IPVOatq&itag=140&source=youtube&requiressl=yes&vprv=1&mime=audio%2Fmp4&ns=TaAiaqvhrWsetsVdwH758SQH&gir=yes&clen=4670606&dur=288.554&lmt=1609818651748054&keepalive=yes&fexp=24001373%2C24007246&c=WEB&rbqsm=fr&txp=5511222&n=Xs-KP4lymM-ZqT4OT6&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cvprv%2Cmime%2Cns%2Cgir%2Cclen%2Cdur%2Clmt&sig=AOq0QJ8wRgIhAKa-cXR3r3cWP2z_vS6kjZ5GlXnWboxvU2WeDIi8_KAUAiEAlt6cUlQpP8BRFK4ASntbOHTiOl6jOmAGqbgpQC_Oxos=&cms_redirect=yes&mh=gL&mip=118.150.192.188&mm=31&mn=sn-q5q5uf-un5l&ms=au&mt=1662692458&mv=m&mvi=1&pl=21&lsparams=mh,mip,mm,mn,ms,mv,mvi,pl&lsig=AG3C_xAwRAIgeS1LHQJxIDkieHMrwnoqSEPoVjQk_RFZ0O3S7A053RgCID4vVKiD5beQ-kXlk8njR1KuWUiaV38ZKN17paLUdUcM',
duration=240000
)
line_bot_api.reply_message(event.reply_token, audio_message)
Location message
位置訊息使用的是LocationSendMessage
,只要將位置經緯度作為參數傳入即可,點開會以預設瀏覽器地圖打開。
def handle_message(event):
message = event.message.text
if '範例位置' in message:
location_message = LocationSendMessage(
title='國壽大樓',
address='Cathaylife',
latitude=25.037412842814803,
longitude=121.55362066034458
)
line_bot_api.reply_message(event.reply_token, location_message)
Template message
Template這邊提供幾種模板的訊息形式讓我們可以套用,例如下面這張圖中line bot回傳的訊息,同時下方有些選項可以點,包含Postback、Like、Youtube:
它是用TemplateSendMessage
包住一個ButtonsTemplate
,其中Buttons裡面有圖片、標題、說明文字,在actions部分則用PostbackAction
、MessageAction
、URIAction
做出超連結按鈕。
def handle_message(event):
message = event.message.text
if '推薦影片' in message :
buttons_template_message = TemplateSendMessage(
alt_text='Buttons template',
template=ButtonsTemplate(
thumbnail_image_url='https://i.ytimg.com/vi/vJO4Fg_iEss/maxresdefault.jpg',
title='小小戀歌',
text='「求婚大作戰」主題曲:小さな恋のうた《小小戀歌》 -粉ミルク (Cover)',
actions=[
PostbackAction(
label='Postback',
display_text='偷偷傳資料成功',
data='action=buy&itemid=1'
),
MessageAction(
label='Like',
text='喜歡'
),
URIAction(
label='Youtube',
uri='https://www.youtube.com/watch?v=vJO4Fg_iEss&list=RDvJO4Fg_iEss&index=1&ab_channel=VickyTsai'
)
]
)
)
line_bot_api.reply_message(event.reply_token, buttons_template_message)
註:PostbackAction的實際應用還不太清楚。
另外,CarouselTemplate
搭配CarouselColumn
可以做出多個ButtonsTemplate
的效果:
def handle_message(event):
message = event.message.text
if '推薦多個影片' in message:
carousel_template_message = TemplateSendMessage(
alt_text='Carousel template',
template=CarouselTemplate(
columns=[
CarouselColumn(
thumbnail_image_url='https://i.ytimg.com/vi/vJO4Fg_iEss/maxresdefault.jpg',
title='小小戀歌',
text='「求婚大作戰」主題曲:小さな恋のうた《小小戀歌》 -粉ミルク (Cover)',
actions=[
MessageAction(
label='Like',
text='喜歡'
),
URIAction(
label='Youtube',
uri='https://www.youtube.com/watch?v=vJO4Fg_iEss&list=RDvJO4Fg_iEss&index=1&ab_channel=VickyTsai'
),
URIAction(
label='更多影片',
uri='https://www.youtube.com/c/Hujikoman'
)
]
),
CarouselColumn(
thumbnail_image_url='https://i.ytimg.com/vi_webp/SX_ViT4Ra7k/maxresdefault.webp',
title='Lemon',
text='米津玄師',
actions=[
MessageAction(
label='Like',
text='喜歡'
),
URIAction(
label='Youtube',
uri='https://www.youtube.com/watch?v=SX_ViT4Ra7k&ab_channel=KenshiYonezu%E7%B1%B3%E6%B4%A5%E7%8E%84%E5%B8%AB'
),
URIAction(
label='更多影片',
uri='https://www.youtube.com/c/KenshiYonezuHACHI'
)
]
)
]
)
)
line_bot_api.reply_message(event.reply_token, carousel_template_message)
Flex message
最後FlexSendMessage
提供更客製化的模板訊息,在官網的flex messages上面有提供Flex Message Simulator,這個產生器可以產出你想要的訊息內容,再把產出的json內容放到contents參數。
def handle_message(event):
message = event.message.text
if '推薦咖啡廳' in message:
flex_message = FlexSendMessage(
alt_text='hello',
contents={
"type": "bubble",
"hero": {
"type": "image",
"url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/01_1_cafe.png",
"size": "full",
"aspectRatio": "20:13",
"aspectMode": "cover",
"action": {
"type": "uri",
"uri": "https://goo.gl/maps/HPaa1aMazBCcgkmA9"
}
},
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": "上島珈琲店",
"weight": "bold",
"size": "xl"
},
{
"type": "box",
"layout": "baseline",
"margin": "md",
"contents": [
{
"type": "icon",
"size": "sm",
"url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
},
{
"type": "icon",
"size": "sm",
"url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
},
{
"type": "icon",
"size": "sm",
"url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
},
{
"type": "icon",
"size": "sm",
"url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
},
{
"type": "icon",
"size": "sm",
"url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gray_star_28.png"
},
{
"type": "text",
"text": "4.0",
"size": "sm",
"color": "#999999",
"margin": "md",
"flex": 0
}
]
},
{
"type": "box",
"layout": "vertical",
"margin": "lg",
"spacing": "sm",
"contents": [
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": "Place",
"color": "#aaaaaa",
"size": "sm",
"flex": 1
},
{
"type": "text",
"text": "106台北市大安區敦化南路1段199號吟龍大廈",
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 5
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": "Time",
"color": "#aaaaaa",
"size": "sm",
"flex": 1
},
{
"type": "text",
"text": "07:30 – 22:00",
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 5
}
]
}
]
}
]
},
"footer": {
"type": "box",
"layout": "vertical",
"spacing": "sm",
"contents": [
{
"type": "button",
"style": "link",
"height": "sm",
"action": {
"type": "uri",
"label": "聯繫我們",
"uri": "https://www.ueshima-coffee.com.tw/"
}
},
{
"type": "button",
"style": "link",
"height": "sm",
"action": {
"type": "uri",
"label": "Google地圖",
"uri": "https://goo.gl/maps/HPaa1aMazBCcgkmA9"
}
},
{
"type": "box",
"layout": "vertical",
"contents": [],
"margin": "sm"
}
],
"flex": 0
}
})
line_bot_api.reply_message(event.reply_token, flex_message)