iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 6
0
Modern Web

宅男的浪漫 - 用 .NET Core 打造 Line 婚禮聊天機器人經驗分享系列 第 6

環保愛地球,回傳電子喜帖

第12 屆iT邦幫忙鐵人賽系列文章 (Day6)

今天要來做電子喜帖功能,節能減碳,環保愛地球

主要傳送是用 Line 的 ImageMessage

這部分跟程式無關 XD 只是分享 template 網站,設計苦手的工程師其實可以考慮一些素材網站,或 template 網站,付點錢就能拿到質感極佳的設計
Wedding Invitation Templates (Free) | Greetings Island
*Create your own wedding invitation cards in minutes with our invitation maker. Download, print or send online with RSVP…*www.greetingsisland.com

Free Greeting Cards & Invitation Templates | Greetings Island
*Customize, download, print & send online. Browse by category Here comes the invitation! Announce your wedding day with…*www.greetingsisland.com

將圖片傳到圖床 (imgur)

Line 發送圖片時候是以 URL,通常我會傳到 imgur 平台產生一個 https 的連結,從上面網站製作好範例喜帖如下:

OnMessageAsync

在前幾篇我們有介紹的OnMessageAsync,我們在這實作接收到文字訊息時候要回傳的訊息,考量到再來使用者的意圖 (intent) 可能會越來越多,我們用一個簡單的 Dictionary 來做處理

使用者的意圖 (intent) 是在做chatbot NLP 或使用 chatbot 一些服務時很常看見的名詞,簡單來講就是當使用者打出這句話時,是想做什麼事

定義一個介面,包含 ReplyAsync 方法,需要傳入回覆所需 replyToken

public interface IReplyIntent

{

Task ReplyAsync(string replyToken);

}

接收文字

protected virtual async Task OnMessageAsync(Event ev)

{

if (ev.message.Type.Equals(LineMessageType.text))

{

// 完整比對使用者輸入的訊息,決定要回傳什麼

var msg = ev.message.Text;

var intents = new Dictionary<string, IReplyIntent>()

{

{ "電子喜帖" ,new WeddingInvitation(lineMessageUtility,lineProfileUtility)},

{ "Default" ,new DefaultIntent(lineMessageUtility,lineProfileUtility)},

};

var intent = intents.ContainsKey(ev.message.Text) ? intents[msg] : intents["Default"];

await intent.ReplyAsync(ev.replyToken);

}

}

定義 ImageMessage.cs

public class ImageMessage : IMessage

{

public LineMessageType Type => LineMessageType.image;

public string OriginalContentUrl { get; set; }

public string PreviewImageUrl { get; set; }

}

新增 WeddingInvitation.cs 並實作

public class WeddingInvitation : IReplyIntent

{

private readonly LineReplyMessageUtility lineMessageUtility;

private readonly LineProfileUtility lineProfileUtility;

public WeddingInvitation(LineReplyMessageUtility _lineMessageUtility, LineProfileUtility _lineProfileUtility)

{

lineMessageUtility = _lineMessageUtility;

lineProfileUtility = _lineProfileUtility;

}

public async Task ReplyAsync(string replyToken)

{

var imageMessage = new ImageMessage()

{

OriginalContentUrl = "https://i.imgur.com/Li0UUul.png",

PreviewImageUrl = "https://i.imgur.com/Li0UUul.png"

};

await lineMessageUtility.ReplyMessageAsync(replyToken, new List<IMessage> {

imageMessage

});

}

}

實作效果

有啥限制嗎?

ImageMessage 在傳送的時候要注意有以下限制

  • URL 最大 1000 字元

  • 一定要是 HTTPS 且加密規範 TLS 1.2 以上

  • 檔案大小上限 200 MB

  • 圖片需為 JPEG or PNG

懶人包,本次學到了什麼?

本篇文章同步發佈於我的 Medium 如果這篇文章對你有幫助,就大力追蹤和拍手鼓掌下去吧 !!


上一篇
回傳不文謅謅的 Line 貼圖
下一篇
有聲有色,傳送婚禮前導預告影片
系列文
宅男的浪漫 - 用 .NET Core 打造 Line 婚禮聊天機器人經驗分享30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言