C#代碼中如何創建Card

C#代碼中如何創建Card

Microsoft.Bot.Connector

Microsoft.Bot.Connector爲微軟官方package【Microsoft.Bot.Connector.dll】
在Bot/Connector/Message Extension中的消息都是通過Activity來承載的【命名空間Microsoft.Bot.Connector,對應的ContentType爲application/vnd.microsoft.activity】,那麼在Activity中如何添加Card對象呢?
談到這裏,其實又可以提到強大的App Studio了,因爲它就提供生成Card預覽和對應代碼的功能。
話不多說,先說下這個功能:

  • 進入Card editor
    在這裏插入圖片描述
  • 選擇Hero Card
    在這裏插入圖片描述
  • 選擇csharp對應的tab,這裏提供了Card對應json數據結構和C#對應的code snippet。有圖上部分是我從代碼中截出來的屬性。
    下部分是preview效果。其實這個就已經足夠我們做測試了。比如希望得到的Card是什麼樣的,然後進行編輯,實時看效果。
    當效果ok後,再放到代碼工程裏。
    在這裏插入圖片描述

CSharp代碼示例

當然,這裏是以Hero Card作爲示例的。也可以按照實際情況,選擇Thumbnail Card或者Adaptive Card。下邊是生成Thumbnail Card,在實際項目中的部分代碼:

        private static ComposeExtensionAttachment GetItemAttachment(ItemInfo item)
        {
            var card = new ThumbnailCard
            {
                Title = item.Name,
                Text = item.Description.Length > 20 ? item.Description.Substring(0, 20) : item.Description,
                Images = new List<CardImage> { new CardImage(item.Image) },
                Subtitle = item.Link,
                Tap = new CardAction() { Type = "postBack", Title = item.Name, Value = "https://docs.microsoft.com/en-us/MicrosoftTeams/teams-overview", Image = item.Image },
            };

            var starBtn = new CardAction() { Type = "messageBack", DisplayText = "Star", Title = "Star", Value = "{\"Id\":\"" + item.Id + "\",\"Star\":true}" };
            var updateItemBtn = new CardAction() { Type = "invoke", DisplayText = "Update " + item.Name, Title = "Update this item", Value = "{\"type\":\"task/fetch\",\"title\":\"Update\",\"Id\":\"" + item.Id + "\"}" };
            card.Buttons = new List<CardAction>() { starBtn, updateItemBtn };


            return card
                .ToAttachment()
                .ToComposeExtensionAttachment();
        }

框架代碼提供了Card和Bot的attachment的方法,方便使用。

如果想看更多的示例代碼,也可以上github上微軟名下找找對應repository,有很多示例代碼。或者有其他可用的repository也有蠻高的參考價值,比如https://github.com/Office365DevOps/microsoft-teams-templates。

如有問題,可以下方留言,共同探討。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章