第12 屆iT邦幫忙鐵人賽系列文章 (Day15)
在上一篇我們介紹如何設定圖文選單,本篇要來介紹如何切換圖文選單,此部分只能用程式來達成,在 Line Business 後台只能設定固定的圖文選單起訖日,有了這功能就可以像網站一樣有網站地圖的概念
今天實作要將 chatbot 隨機切換不同的圖文選單,給使用者不同的體驗,今天的範例圖片在這 https://i.imgur.com/pupYvXr.jpg
CreateRichMenuAsync
原本預設的 Rich Menu 是寫在 SetDefaultRichMenuAsync,我們做點重構,讓Rich Menu 的物件是從外部傳入,因為我們現在要設定多個選單
public async Task<Richmenu> CreateRichMenuAsync(CreateRichmenu richmenu)
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), lineMessageApiBaseUrl))
{
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}");
var postJson = JsonConvert.SerializeObject(richmenu, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
}
});
request.Content = new StringContent(postJson);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await httpClient.SendAsync(request);
var results = await response.Content.ReadAsStringAsync();
var richmenu_res = JsonConvert.DeserializeObject<Richmenu>(results);
return richmenu_res;
};
}
}
RichMenuUtility
我們將這些定義 Rich Menu的程式抽到這邊
public static class RichMenuUtility
{
public static CreateRichmenu GetDefault()
{
var defaultRichMenu = new CreateRichmenu();
defaultRichMenu.size = new CreateSize(1200, 810);
defaultRichMenu.selected = true;
defaultRichMenu.name = "Default RichMenu";
defaultRichMenu.chatBarText = "Kyle's Wedding";
defaultRichMenu.areas = new List<CreateArea>()
{
new CreateArea(boundx:0,boundy:0,width:800,height:810, _action: new MessageAction("婚紗輪播"))
};
return defaultRichMenu;
}
public static CreateRichmenu GetSecondOne()
{
var defaultRichMenu = new CreateRichmenu();
defaultRichMenu.size = new CreateSize(1200, 810);
defaultRichMenu.selected = true;
defaultRichMenu.name = "Second One";
defaultRichMenu.chatBarText = "Kyle's Wedding";
defaultRichMenu.areas = new List<CreateArea>()
{
new CreateArea(boundx:0,boundy:0,width:800,height:810, _action: new MessageAction("婚紗輪播"))
};
return defaultRichMenu;
}
}
程式就不像 Line Business 後台那麼方便有一些範本,未來如果要封裝 SDK 我可能會考慮將後台的那些範本封裝起來,只要設定圖片.按鈕事件即可
InitRickMenu
修改上一篇,我們 GetRichMenuListAsync 我們改回傳id即可,在設定好圖文選單時也 Add 到 ID 陣列裡,最後,我們隨機取得任一個 ID 做顯示的設定
實際畫面就不 Demo 了,RichMenu會在每次進入聊天頁面的時候隨機切換,但因為會跑出我朋友的列表不方便 Demo XD…當然這需求很奇怪,實際上應該是做成像多層選單方式,去逐步切換,且可以返回主選單的概念,這樣就讓 Line Chatbot 也像網頁一樣有上一頁 下一頁啦~
如何上傳 多個 Rich Menu 圖片
https://developers.line.biz/en/reference/messaging-api/#upload-rich-menu-image
如何切換 Rich Menu 圖片
https://developers.line.biz/en/reference/messaging-api/#set-default-rich-menu
本篇文章同步發佈於我的 Medium 如果這篇文章對你有幫助,就大力追蹤和拍手鼓掌下去吧 !!